<?php

namespace app\common\logic;

use app\common\model\Invoice;
use app\common\model\Member;
use app\common\model\Seller;
use app\service\GoodsService;
use think\Model;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 逻辑层模型
 */
class Buy extends Model
{
    /**
     * 会员信息
     * @var array
     */
    private $_member_info = array();

    /**
     * 下单数据
     * @var array
     */
    private $_order_data = array();

    /**
     * 表单数据
     * @var array
     */
    private $_post_data = array();

    /**
     * buy_1.logic 对象
     * @var obj
     */
    private $_logic_buy_1;

    public function __construct()
    {
        $this->_logic_buy_1 = new Buy_1();
    }

    /**
     * 购买第一步
     * @param type $cart_id
     * @param type $ifcart
     * @param type $member_id
     * @param type $store_id
     * @param type $extra 额外特殊判断处理数据，比如拼团功能
     * @return type
     */
    public function buyStep1($cart_id, $ifcart, $member_id, $store_id, $extra = array(), $is_install = '0', $address_id = '0')
    {
        //第一次进来的时候判断用户是否选择了地址，如果没有选择地址的话，找到用户的默认地址
        if (!$address_id) {
            $address_where = array('member_id' => $member_id, 'address_is_default' => 1);
            $address_info = model('address')->getDefaultAddressInfo($address_where);
            #如果用户没默认地址
            if (empty($address_info)) {
                $address_id = 0;
            } else {
                $address_id = $address_info['address_id'];
            }
        }

        //得到购买商品信息
        if ($ifcart) {
            //购物车
            $result = $this->getCartList($cart_id, $member_id);
            // p($result);die;
        } else {
            //直接购买
            $result = $this->getGoodsList($cart_id, $member_id, $store_id, $extra, $is_install, $address_id);
            //p($result);die;
        }
        if (!$result['code']) {
            return $result;
        }
        //p($result);die;

        //zjw  处理最终价格
        //得到页面所需要数据：收货地址、发票、代金券、预存款、商品列表等信息
        $result = $this->getBuyStep1Data($member_id, $result['data'], $ifcart, $is_install, $address_id);

        //  p($result);die;
        return $result;
    }

    /**
     * 第一步：处理购物车
     * @param type $cart_id 购物车
     * @param type $member_id 会员编号
     * @param type $extra 额外特殊判断处理数据，比如拼团功能
     * @return type
     */
    public function getCartList($cart_id, $member_id, $extra = array())
    {
        $cart_model = model('cart');

        //取得POST ID和购买数量
        $buy_items = $this->_parseItems($cart_id);
        if (empty($buy_items)) {
            return ds_callback(false, '所购商品无效');
        }

        if (count($buy_items) > 50) {
            return ds_callback(false, '一次最多只可购买50种商品');
        }

        //购物车列表
        $condition = array('cart_id' => array('in', array_keys($buy_items)), 'buyer_id' => $member_id);
        $cart_list = $cart_model->getCartList('db', $condition);
        // p($cart_list);die;
        //购物车列表 [得到最新商品属性及促销信息]
        $cart_list = $this->_logic_buy_1->getGoodsCartList($cart_list);
        //商品列表 [优惠套装子商品与普通商品同级罗列]
        $goods_list = $this->_getGoodsList($cart_list);
        // p($goods_list);die;
        //以店铺下标归类
        $store_cart_list = $this->_getStoreCartList($cart_list);
        return ds_callback(true, '', array('goods_list' => $goods_list, 'store_cart_list' => $store_cart_list));
    }

    /**
     * 第一步：处理立即购买
     * @param type $cart_id 购物车
     * @param type $member_id 会员编号
     * @param type $store_id 店铺编号
     * @param type $extra 额外特殊判断处理数据，比如拼团功能
     * @return type
     */
    public function getGoodsList($cart_id, $member_id, $store_id, $extra = array(), $is_install = '0', $address_id = '0')
    {
        //取得POST ID和购买数量
        $buy_items = $this->_parseItems($cart_id);
        if (empty($buy_items)) {
            return ds_callback(false, '所购商品无效');
        }
        $goods_info['is_install'] = $is_install;
        $goods_id = key($buy_items);
        $quantity = current($buy_items);

        //商品信息[得到最新商品属性及促销信息]
        $goods_info = $this->_logic_buy_1->getGoodsOnlineInfo($goods_id, intval($quantity), $extra, $member_id);

        $brand_info = db('goods')->alias('g')
            ->join('brand b', 'b.brand_id = g.brand_id')
            ->where(['goods_id' => $goods_info['goods_id']])
            ->find();
        $goods_info['goods_name'] = $brand_info['brand_name'] . '  ' . $goods_info['goods_name'];
        // p($goods_info);die;
        if (empty($goods_info)) {
            return ds_callback(false, '商品已下架或不存在');
        }

        //不能购买自己店铺的商品
        if ($goods_info['store_id'] == $store_id) {
            return ds_callback(false, '不能购买自己店铺的商品');
        }
        $store_id = get_parent_store_id();
        //p($store_id);die; 130602
        $supplier_type = get_supplier_type();

        #计算安装费
        if ($address_id) {
            $address_info = db('address')->where(['address_id' => $address_id])->find();
            if (!$address_info) {
                return json_fail_return('地址不存在');
            }
            $address_area_id = $address_info['area_id'];  #地址的区id
        } else {
            $address_area_id = 0; #地址的区id
        }

        //如果有安装费
        if ($is_install == 1) {
            //找到安装工时，计算安装费
            if ($goods_info['install_money']) {
                #安装费
                $sum_install_money = get_install_money($address_area_id, (float)$goods_info['install_money']);
            } else {
                $sum_install_money = 0;
            }
        }
        #shen 判断价格是否相同  (算出 商品的真实价格 包含：供应商的价格，平台的价格，以及运营商的价格和安装费)
        if ($supplier_type == 1) {
            #加价
            $y_goods_info = db('y_goods')->where('store_id', $store_id)->where('goods_id', $goods_info['goods_id'])->find();
            // p($goods_info);die;

            if ($is_install == 1) {
                #含有安装
                $goods_info['goods_price'] = $sum_install_money + (float)$goods_info['gu_final_price'] + (float)$y_goods_info['price'];
            } else {
                $goods_info['goods_price'] = (float)$goods_info['gu_final_price'] + (float)$y_goods_info['price'];
            }
        } else {
            #按照提成走
            if ($is_install == 1) {
                #含有安装
                $goods_info['goods_price'] = $sum_install_money + (float)$goods_info['ti_final_price'];
            } else {
                $goods_info['goods_price'] = (float)$goods_info['ti_final_price'];
            }
        }

        $config = db('config')->where('code', 'qiniu_http')->find();
        $goods_info['goods_image_url'] = $config['value'] . '/' . $goods_info['goods_image'];


        //进一步处理数组
        $store_cart_list = array();
        $goods_list = array();
        $goods_list[0] = $store_cart_list[$goods_info['store_id']][0] = $goods_info;

        return ds_callback(true, '', array('goods_list' => $goods_list, 'store_cart_list' => $store_cart_list));
    }

    /**
     * 购买第一步：返回商品、促销、地址、发票等信息，然后交前台抛出
     * @param unknown $member_id
     * @param unknown $data 商品信息
     * @return
     */
    public function getMansongData($member_id, $data, $ifcart = '0')
    {
        //list($goods_list, $store_cart_list) = $data;
        $goods_list = $data['goods_list'];
        $store_cart_list = $data['store_cart_list'];
        //p($store_cart_list);die;

        //定义返回数组
        $result = array();
        //商品金额计算(分别对每个商品/优惠套装小计、每个店铺小计)
        list($mansong_list, $mansong_price) = $this->_logic_buy_1->calcMansongList($store_cart_list, $ifcart);
        $result['mansong_list'] = $mansong_list;
        $result['mansong_price'] = $mansong_price;

        return ds_callback(true, '', $result);
    }

    /**
     * 购买第一步：返回商品、促销、地址、发票等信息，然后交前台抛出
     * @param unknown $member_id
     * @param unknown $data 商品信息
     * @return
     */
    public function getBuyStep1Data($member_id, $data, $ifcart = '0', $is_install = '0', $address_id = '0')
    {
        //list($goods_list, $store_cart_list) = $data;
        $goods_list = $data['goods_list'];
        $store_cart_list = $data['store_cart_list'];
        //p($store_cart_list);die;

        //定义返回数组
        $result = array();
        //商品金额计算(分别对每个商品/优惠套装小计、每个店铺小计)
        list($store_cart_list, $store_goods_total, $store_goods_discount) = $this->_logic_buy_1->calcCartList($store_cart_list, $ifcart, $is_install, $address_id);
        //p($store_cart_list);die;
        $result['store_cart_list'] = $store_cart_list;
        $result['store_goods_total'] = $store_goods_total;  #每个店铺的商品总价（不包含运费）
        $result['store_goods_discount'] = $store_goods_discount; #每个店铺一共折扣了多少钱
        // var_dump($result['store_goods_discount']);die;
        //zjw 判断是走折扣的金额 还是没折扣的金额
        $new_prcie = $store_goods_total;

        //取得店铺优惠 - 满即送(赠品列表，店铺满送规则列表,没用到)
        // list($store_premiums_list, $store_mansong_rule_list) = $this->_logic_buy_1->getMansongruleCartListByTotal($store_goods_total,$goods_list);
        list($store_premiums_list, $store_mansong_rule_list) = $this->_logic_buy_1->getMansongruleCartListByTotal($new_prcie, $goods_list);
        //p($store_premiums_list);die;
        $result['store_premiums_list'] = $store_premiums_list;
        $result['store_mansong_rule_list'] = $store_mansong_rule_list;

        //重新计算优惠后(满即送)的店铺实际商品总金额
        $store_goods_total = $this->_logic_buy_1->reCalcGoodsTotal($store_goods_total, $store_mansong_rule_list, 'mansong');

        //返回店铺可用的代金券
        $store_voucher_list = $this->_logic_buy_1->getStoreAvailableVoucherList($store_goods_total, $member_id);
        $result['store_voucher_list'] = $store_voucher_list;

        //返回需要计算运费的店铺ID数组 和 不需要计算运费(满免运费活动的,没用到)
        list($need_calc_sid_list, $cancel_calc_sid_list) = $this->_logic_buy_1->getStoreFreightDescList($store_goods_total);
        $result['need_calc_sid_list'] = $need_calc_sid_list;
        $result['cancel_calc_sid_list'] = $cancel_calc_sid_list;

        //将商品ID、数量、售卖区域、运费序列化，加密，输出到模板，选择地区AJAX计算运费时作为参数使用
        $freight_list = $this->_logic_buy_1->getStoreFreightList($goods_list, array_keys($cancel_calc_sid_list));
        $result['freight_list'] = $this->buyEncrypt($freight_list, $member_id);

        //输出用户默认收货地址
        if ($address_id) {
            $address_where = array('address_id' => $address_id);
        } else {
            $address_where = array('member_id' => $member_id, 'address_is_default' => 1);
        }
        $result['address_info'] = model('address')->getDefaultAddressInfo($address_where);
        //p($result['address_info']);die;

        //zjw  组装满减信息 -------------------start--------------------------
        list($mansong_list, $mansong_price, $new_price, $total_difference, $price_difference, $store_cart_list, $voucher_list) = $this->_logic_buy_1->calcMansongList($store_cart_list, $ifcart, $is_install, $member_id, $address_id);
        // p($mansong_list);die;
        $result['mansong_list'] = $mansong_list;
        $result['mansong_price'] = $mansong_price;
        $result['new_price'] = $new_price;
        $result['total_difference'] = $total_difference;  #（总商品价格） 不包含运费的商品总价 + 运费 + 满减 +优惠劵的值   是前端最终展示的值
        $result['price_difference'] = $price_difference;
        //算上满送的  新组装的数据
        $result['store_cart_list'] = $store_cart_list;
        $result['voucher_list'] = $voucher_list; #返回优惠劵列表
        //                 -------------------end--------------------------

        //获取配送方式
        list($distribution_type) = $this->_logic_buy_1->distributionList($store_cart_list);
        $result['distribution_type'] = $distribution_type;

        //获取用户表信息（返回积分）
        list($integral_ratio) = $this->_logic_buy_1->integral_ratioList($store_cart_list, $member_id);
        $result['integral_ratio'] = $integral_ratio;

        //输出有货到付款时，在线支付和货到付款及每种支付下商品数量和详细列表
        $pay_goods_list = $this->_logic_buy_1->getOfflineGoodsPay($goods_list);
        if (!empty($pay_goods_list['offline'])) {
            $result['pay_goods_list'] = $pay_goods_list;
            $result['ifshow_offpay'] = true;
        } else {
            //如果所购商品只支持线上支付，支付方式不允许修改
            $result['deny_edit_payment'] = true;
            $result['pay_goods_list'] = $pay_goods_list;
            $result['ifshow_offpay'] = FALSE;
        }

        //发票 :只有所有商品都支持增值税发票才提供增值税发票
        $vat_deny = false;
        foreach ($goods_list as $goods) {
            if (!intval($goods['goods_vat'])) {
                $vat_deny = true;
                break;
            }
        }

        //不提供增值税发票时抛出true(模板使用)
        $result['vat_deny'] = $vat_deny;
        $result['vat_hash'] = $this->buyEncrypt($result['vat_deny'] ? 'deny_vat' : 'allow_vat', $member_id);

        //        $invoice = new Invoice();
        //输出默认使用的发票信息
        // TODO 发票
        /*$inv_info = model('invoice')->getDefaultInvoiceInfo(array('member_id' => $member_id));
        if ($inv_info['invoice_state'] == '2' && !$vat_deny) {
            $inv_info['content'] = '增值税发票 ' . $inv_info['invoice_company'] . ' ' . $inv_info['invoice_company_code'] . ' ' . $inv_info['invoice_reg_addr'];
        }
        elseif ($inv_info['invoice_state'] == '2' && $vat_deny) {
            $inv_info = array();
            $inv_info['content'] = '不需要发票';
        }
        elseif (!empty($inv_info)) {
            $inv_info['content'] = '普通发票 ' . $inv_info['invoice_title'] . ' ' . $inv_info['invoice_code']. ' ' . $inv_info['invoice_content'];
        }
        else {
            $inv_info = array();
            $inv_info['content'] = '不需要发票';
        }
        $result['inv_info'] = $inv_info;*/

        $buyer_info = model('member')->getMemberInfoByID($member_id);
        if (floatval($buyer_info['available_predeposit']) > 0) {
            $result['available_predeposit'] = $buyer_info['available_predeposit'];
        }
        if (floatval($buyer_info['available_rc_balance']) > 0) {
            $result['available_rc_balance'] = $buyer_info['available_rc_balance'];
        }
        // $result['member_paypwd'] = $buyer_info['member_paypwd'] ? true : false;

        return ds_callback(true, '', $result);
    }

    /**
     * 服务单创建订单
     * @param array $post
     * @param int $member_id
     * @param string $member_name
     * @param string $member_email
     * @return array
     */
    public function serviceCreate($post, $member_id, $member_name, $member_email)
    {
        $this->_member_info['member_id'] = $member_id;
        $this->_member_info['member_name'] = $member_name;
        $this->_member_info['member_email'] = $member_email;
        $this->_post_data = $post;

        //生成订单
        $dd = $this->_serviceCreate4($post, $member_id, $member_name, $member_email);
    }

    /**
     * 预订单生成订单
     * @param array $input
     * @return array array(支付单sn,订单列表) ,$voucher_id
     * @throws Exception
     */
    private function _serviceCreate4($data, $member_id, $member_name, $member_email)
    {
        $order_model = new \app\common\model\Order();

        //遍历传过来的数据
        foreach ($data as $key => $value) {
            //商品总价
            $goods_amount = 0;
            // 1、遍历所有商品 获取信息
            foreach ($value['goodsInfo'] as $k => $v) {
                $goods_info = db('goods')->where(['goods_id' => $v['goods_id']])->find();
                $goods_amount += $goods_info['goods_price'] * $v['num'];
            }


            // 2、生成order表数据
            $order = array();
            $pay_sn = makePaySn($member_id);
            $yys_id = get_parent_store_id();
            $yys_info = db('store')->where('store_id', $yys_id)->find();

            $order['order_sn'] = $this->_logic_buy_1->makeOrderSn($order_pay_id);
            $order['pay_sn'] = $pay_sn;
            $order['service_order_id'] = $value['service_order_id'];
            // $order['store_id'] = ;
            // $order['store_name'] = ;
            $order['buyer_id'] = $member_id;
            $order['buyer_name'] = $member_name;
            $order['member_email'] = $member_email;
            $order['add_time'] = TIMESTAMP;
            // $order['payment_code'] = ;
            // $order['payment_time'] = ;
            $order['goods_amount'] = $goods_amount;
            $order['order_amount'] = $goods_amount;
            $order['order_state'] = 10;
            $order['order_type'] = 2;
            $order['yys_id'] = $yys_id;
            $order['yys_name'] = $yys_info['store_name'];
            if ($order['payment_code'] == "") {
                $order['payment_code'] = "offline";
            }
            $order_id = $order_model->addOrder($order);
            if (!$order_id) {
                exception('订单保存失败[未生成订单数据]');
            }

            $order['order_id'] = $order_id;
            $order_list[$order_id] = $order;

            //3、生成订单信息扩展表
            $input_address_info = model('address')->getAddressInfo(array('address_id' => $value['address_id']));

            $address_info = db('address')->where(['address_id' => $value['address_id']])->find();

            $order_common['order_id'] = $order_id;
            // $order_common['store_id'] = ;
            $order_common['daddress_id'] = $value['address_id'];
            $order_common['reciver_name'] = $address_info['address_realname'];
            $order_common['reciver_info'] = $input_address_info;
            $order_common['reciver_city_id'] = $address_info['city_id'];

            $order_common_id = $order_model->addOrdercommon($order_common);
            if (!$order_common_id) {
                exception('订单保存失败[未生成订单扩展数据]');
            }

            //4、生成订单商品表
            foreach ($value['goodsInfo'] as $kk => $vv) {
                $goods_info = db('goods')->where(['goods_id' => $v['goods_id']])->find();
                if (!$goods_info['state'] || !$goods_info['storage_state']) {
                    exception('部分商品已经下架或库存不足，请重新选择');
                }

                $order_goods[$kk]['order_id'] = $order_id;
                $order_goods[$kk]['goods_id'] = $v['goods_id'];
                $order_goods[$kk]['goods_name'] = $goods_info['goods_name'];

                $order_goods[$kk]['goods_price'] = $goods_info['goods_price'];

                $order_goods[$kk]['goods_num'] = $vv['num'];
                $order_goods[$i]['goods_image'] = $goods_info['goods_image'];
                $order_goods[$kk]['store_id'] = $member_id;
                $order_goods[$i]['buyer_id'] = $member_id;

                $order_goods[$kk]['spec_values'] = $goods_info['spec_values'];
                $order_goods[$kk]['is_install'] = $goods_info['is_install'];

                $insert = $order_model->addOrdergoods($order_goods);
                if (!$insert) {
                    exception('订单保存失败[未生成商品数据]');
                }
                $order_list[$order_id]['order_goods'] = $order_goods;
            }

            //5、生成大订单数据
            $total = $goods_amount;
            $order_ids_array = array_keys($order_list);
            $order_ids = implode(',', $order_ids_array);
            $total['order_ids'] = $order_ids;
            $order_goods_info = db('ordergoods')->where('order_id', 'in', $order_ids)->select();

            if (!empty($order_goods_info)) {
                $total['goods_ids'] = implode(',', array_column($order_goods_info, 'goods_id'));
                $total['ordergoods_ids'] = implode(',', array_column($order_goods_info, 'rec_id'));
            }
            $total['order_status'] = 0;
            $total['order_sn'] = time() . '123';
            $total['pay_sn'] = $pay_sn;
            $total['create_time'] = time();
            $total['member_name'] = $member_name;
            $total['user_id'] = $member_id;
            $total['user_name'] = $address_info['address_realname'];
            $total['phone'] = $address_info['address_tel_phone'];
            $total['user_address'] = $address_info['area_info'] . ' ' . $address_info['address_detail'];

            $Id = db('app_order')->insertGetId($total);


            $aa = db('order')->data(['apporder_id' => $Id])->where('order_id', 'in', $order_id)->update();

            $aa = db('order')->data(['apporder_id' => $Id])->where('order_id', 'in', $order_id)->update();
        }
    }


    /**
     * 购买第二步
     * @param array $post
     * @param int $member_id
     * @param string $member_name
     * @param string $member_email
     * @return array
     */
    public function buyStep2($post, $member_id, $member_name, $member_email)
    {

        $this->_member_info['member_id'] = $member_id;
        $this->_member_info['member_name'] = $member_name;
        $this->_member_info['member_email'] = $member_email;
        $this->_post_data = $post;

        try {

            $order_model = model('order');
            $order_model->startTrans();

            //第1步 表单验证
            $aa = $this->_createOrderStep1();

            // p($aa);die;
            //第2步 得到购买商品信息
            $bb = $this->_createOrderStep2();
            //p($bb);die;
            // echo 111;die;
            //第3步 得到购买相关金额计算等信息
            $cc = $this->_createOrderStep3();

            //p($cc);die;

            //第4步 生成订单  ,$post['deduction_ids']
            $dd = $this->_createOrderStep4($post['is_integral'], $post['amount_reduction'], $post['voucher_id'], $post['deduction_ids']);
            // p($dd);die;


            //第5步 处理预存款
            $ee = $this->_createOrderStep5();

            // p($ee);die;
            //

            //第6步 订单后续处理
            $gg = $this->_createOrderStep6();
            // p($gg);die;
            $order_model->commit();
            return ds_callback(true, '', $this->_order_data);
        } catch (\think\Exception $e) {
            $this->rollback();
            return ds_callback(false, $e->getMessage());
        }
    }

    /**
     * 生成推广记录
     * @param array $order_list
     */
    public function addOrderInviter($order_list = array())
    {
        if (!config('inviter_open')) {
            return;
        }
        if (empty($order_list) || !is_array($order_list))
            return;
        $inviter_ratio_1 = config('inviter_ratio_1');
        $inviter_ratio_2 = config('inviter_ratio_2');
        $inviter_ratio_3 = config('inviter_ratio_3');
        $orderinviter_model = model('orderinviter');
        foreach ($order_list as $order_id => $order) {
            foreach ($order['order_goods'] as $goods) {
                //查询商品的分销信息
                $goods_common_info = db('goodscommon')->alias('gc')->join('__GOODS__ g', 'g.goods_commonid=gc.goods_commonid')->where('g.goods_id=' . $goods['goods_id'])->field('gc.goods_commonid,gc.inviter_open,gc.inviter_ratio_1,gc.inviter_ratio_2,gc.inviter_ratio_3')->find();
                if (!$goods_common_info['inviter_open']) {
                    continue;
                }
                $goods_amount = $goods['goods_price'] * $goods['goods_num'];
                $inviter_ratios = array(
                    ($goods_common_info['inviter_ratio_1'] > $inviter_ratio_1 ? $inviter_ratio_1 : $goods_common_info['inviter_ratio_1']),
                    ($goods_common_info['inviter_ratio_2'] > $inviter_ratio_2 ? $inviter_ratio_2 : $goods_common_info['inviter_ratio_2']),
                    ($goods_common_info['inviter_ratio_3'] > $inviter_ratio_3 ? $inviter_ratio_3 : $goods_common_info['inviter_ratio_3']),
                );
                //判断买家是否是分销员
                if (config('inviter_return')) {
                    if (db('inviter')->where('inviter_state=1 AND inviter_id=' . $order['buyer_id'])->value('inviter_id')) {
                        if (isset($inviter_ratios[0]) && floatval($inviter_ratios[0]) > 0) {
                            $money_1 = round($inviter_ratios[0] / 100 * $goods_amount, 2);
                            if ($money_1 > 0) {

                                //生成推广记录
                                db('orderinviter')->insert(array(
                                    'orderinviter_addtime' => TIMESTAMP,
                                    'orderinviter_store_name' => $order['store_name'],
                                    'orderinviter_goods_amount' => $goods_amount,
                                    'orderinviter_goods_quantity' => $goods['goods_num'],
                                    'orderinviter_order_type' => 0,
                                    'orderinviter_store_id' => $goods['store_id'],
                                    'orderinviter_goods_commonid' => $goods_common_info['goods_commonid'],
                                    'orderinviter_goods_id' => $goods['goods_id'],
                                    'orderinviter_level' => 1,
                                    'orderinviter_goods_name' => $goods['goods_name'],
                                    'orderinviter_order_id' => $order_id,
                                    'orderinviter_order_sn' => $order['order_sn'],
                                    'orderinviter_member_id' => $order['buyer_id'],
                                    'orderinviter_member_name' => $order['buyer_name'],
                                    'orderinviter_money' => $money_1,
                                    'orderinviter_remark' => '获得分销员返佣，佣金比例' . $inviter_ratios[0] . '%，订单号' . $order['order_sn'],
                                ));
                            }
                        }
                    }
                }
                //一级推荐人
                $inviter_1_id = db('member')->where('member_id', $order['buyer_id'])->value('inviter_id');
                if (!$inviter_1_id || !db('inviter')->where('inviter_state=1 AND inviter_id=' . $inviter_1_id)->value('inviter_id')) {
                    continue;
                }


                $inviter_1 = db('member')->where('member_id', $inviter_1_id)->field('inviter_id,member_id,member_name')->find();
                if ($inviter_1 && isset($inviter_ratios[0]) && floatval($inviter_ratios[0]) > 0) {
                    $money_1 = round($inviter_ratios[0] / 100 * $goods_amount, 2);
                    if ($money_1 > 0) {

                        //生成推广记录
                        db('orderinviter')->insert(array(
                            'orderinviter_addtime' => TIMESTAMP,
                            'orderinviter_store_name' => $order['store_name'],
                            'orderinviter_goods_amount' => $goods_amount,
                            'orderinviter_goods_quantity' => $goods['goods_num'],
                            'orderinviter_order_type' => 0,
                            'orderinviter_store_id' => $goods['store_id'],
                            'orderinviter_goods_commonid' => $goods_common_info['goods_commonid'],
                            'orderinviter_goods_id' => $goods['goods_id'],
                            'orderinviter_level' => 1,
                            'orderinviter_goods_name' => $goods['goods_name'],
                            'orderinviter_order_id' => $order_id,
                            'orderinviter_order_sn' => $order['order_sn'],
                            'orderinviter_member_id' => $inviter_1['member_id'],
                            'orderinviter_member_name' => $inviter_1['member_name'],
                            'orderinviter_money' => $money_1,
                            'orderinviter_remark' => '获得一级推荐佣金，佣金比例' . $inviter_ratios[0] . '%，推荐关系' . $inviter_1['member_name'] . '->' . $order['buyer_name'] . '，订单号' . $order['order_sn'],
                        ));
                    }
                }
                if (config('inviter_level') <= 1) {
                    continue;
                }
                //二级推荐人
                $inviter_2_id = db('member')->where('member_id', $inviter_1_id)->value('inviter_id');
                if (!$inviter_2_id || !db('inviter')->where('inviter_state=1 AND inviter_id=' . $inviter_2_id)->value('inviter_id')) {
                    continue;
                }
                $inviter_2 = db('member')->where('member_id', $inviter_2_id)->field('inviter_id,member_id,member_name')->find();
                if ($inviter_2 && isset($inviter_ratios[1]) && floatval($inviter_ratios[1]) > 0) {
                    $money_2 = round($inviter_ratios[1] / 100 * $goods_amount, 2);
                    if ($money_2 > 0) {

                        //生成推广记录
                        db('orderinviter')->insert(array(
                            'orderinviter_addtime' => TIMESTAMP,
                            'orderinviter_store_name' => $order['store_name'],
                            'orderinviter_goods_amount' => $goods_amount,
                            'orderinviter_goods_quantity' => $goods['goods_num'],
                            'orderinviter_order_type' => 0,
                            'orderinviter_store_id' => $goods['store_id'],
                            'orderinviter_goods_commonid' => $goods_common_info['goods_commonid'],
                            'orderinviter_goods_id' => $goods['goods_id'],
                            'orderinviter_level' => 2,
                            'orderinviter_goods_name' => $goods['goods_name'],
                            'orderinviter_order_id' => $order_id,
                            'orderinviter_order_sn' => $order['order_sn'],
                            'orderinviter_member_id' => $inviter_2['member_id'],
                            'orderinviter_member_name' => $inviter_2['member_name'],
                            'orderinviter_money' => $money_2,
                            'orderinviter_remark' => '获得二级推荐佣金，佣金比例' . $inviter_ratios[1] . '%，推荐关系' . $inviter_2['member_name'] . '->' . $inviter_1['member_name'] . '->' . $order['buyer_name'] . '，订单号' . $order['order_sn'],
                        ));
                    }
                }
                if (config('inviter_level') <= 2) {
                    continue;
                }
                //三级推荐人
                $inviter_3_id = db('member')->where('member_id', $inviter_2_id)->value('inviter_id');
                if (!$inviter_3_id || !db('inviter')->where('inviter_state=1 AND inviter_id=' . $inviter_3_id)->value('inviter_id')) {
                    continue;
                }
                $inviter_3 = db('member')->where('member_id', $inviter_3_id)->field('inviter_id,member_id,member_name')->find();
                if ($inviter_3 && isset($inviter_ratios[2]) && floatval($inviter_ratios[2]) > 0) {
                    $money_3 = round($inviter_ratios[2] / 100 * $goods_amount, 2);
                    if ($money_3 > 0) {

                        //生成推广记录
                        db('orderinviter')->insert(array(
                            'orderinviter_addtime' => TIMESTAMP,
                            'orderinviter_store_name' => $order['store_name'],
                            'orderinviter_goods_amount' => $goods_amount,
                            'orderinviter_goods_quantity' => $goods['goods_num'],
                            'orderinviter_order_type' => 0,
                            'orderinviter_store_id' => $goods['store_id'],
                            'orderinviter_goods_commonid' => $goods_common_info['goods_commonid'],
                            'orderinviter_goods_id' => $goods['goods_id'],
                            'orderinviter_level' => 3,
                            'orderinviter_goods_name' => $goods['goods_name'],
                            'orderinviter_order_id' => $order_id,
                            'orderinviter_order_sn' => $order['order_sn'],
                            'orderinviter_member_id' => $inviter_3['member_id'],
                            'orderinviter_member_name' => $inviter_3['member_name'],
                            'orderinviter_money' => $money_3,
                            'orderinviter_remark' => '获得三级推荐佣金，佣金比例' . $inviter_ratios[2] . '%，推荐关系' . $inviter_3['member_name'] . '->' . $inviter_2['member_name'] . '->' . $inviter_1['member_name'] . '->' . $order['buyer_name'] . '，订单号' . $order['order_sn'],
                        ));
                    }
                }
            }
        }
    }

    /**
     * 删除购物车商品
     * @param unknown $ifcart
     * @param unknown $cart_ids
     */
    public function delCart($ifcart, $member_id, $cart_ids)
    {
        if (!$ifcart || !is_array($cart_ids))
            return;

        $cart_id_str = implode(',', $cart_ids);

        if (preg_match('/^[\d,]+$/', $cart_id_str)) {
            \mall\queue\QueueClient::push('delCart', array('buyer_id' => $member_id, 'cart_ids' => $cart_ids));
        }
    }

    /**
     * 选择不同地区时，异步处理并返回每个店铺总运费以及本地区是否能使用货到付款
     * 如果店铺统一设置了满免运费规则，则售卖区域无效
     * 如果店铺未设置满免规则，且使用售卖区域，按售卖区域计算，如果其中有商品使用相同的售卖区域，则两种商品数量相加后再应用该售卖区域计算（即作为一种商品算运费）
     * 如果未找到售卖区域，按免运费处理
     * 如果没有使用售卖区域，商品运费按快递价格计算，运费不随购买数量增加
     */
    public function changeAddr($freight_hash, $city_id, $area_id, $member_id)
    {
        //$city_id计算售卖区域,$area_id计算货到付款
        $city_id = intval($city_id);
        $area_id = intval($area_id);
        if ($city_id <= 0 || $area_id <= 0)
            return null;

        //将hash解密，得到运费信息(店铺ID，运费,售卖区域ID,购买数量),hash内容有效期为1小时
        $freight_list = $this->buyDecrypt($freight_hash, $member_id);

        //算运费
        $store_freight_list = $this->_logic_buy_1->calcStoreFreight($freight_list, $city_id);

        $data = array();
        $data['state'] = empty($store_freight_list) ? 'fail' : 'success';
        $data['content'] = $store_freight_list;

        //是否能使用货到付款(只有包含平台店铺的商品才会判断)
        //$if_include_platform_store = array_key_exists(DEFAULT_PLATFORM_STORE_ID,$freight_list['iscalced']) || array_key_exists(DEFAULT_PLATFORM_STORE_ID,$freight_list['nocalced']);

        //$offline_store_id_array = model('store')->getOwnShopIds();
        $order_platform_store_ids = array();

        if (!empty($freight_list['iscalced']) && is_array($freight_list['iscalced']))
            foreach (array_keys($freight_list['iscalced']) as $k)
                $order_platform_store_ids[$k] = null;

        if (!empty($freight_list['nocalced']) && is_array($freight_list['nocalced']))
            foreach (array_keys($freight_list['nocalced']) as $k)
                //if (in_array($k, $offline_store_id_array))
                $order_platform_store_ids[$k] = null;

        //if ($order_platform_store_ids) {
        $allow_offpay_batch = model('offpayarea')->checkSupportOffpayBatch($area_id, array_keys($order_platform_store_ids));
        /*
                //JS验证使用
                $data['allow_offpay'] = array_filter($allow_offpay_batch) ? '1' : '0';
                $data['allow_offpay_batch'] = $allow_offpay_batch;
            } else {*/
        //JS验证使用
        $data['allow_offpay'] = array_filter($allow_offpay_batch) ? '1' : '0';
        $data['allow_offpay_batch'] = $allow_offpay_batch;
        //}

        //PHP验证使用
        $data['offpay_hash'] = $this->buyEncrypt($data['allow_offpay'] ? 'allow_offpay' : 'deny_offpay', $member_id);
        $data['offpay_hash_batch'] = $this->buyEncrypt($data['allow_offpay_batch'], $member_id);

        return $data;
    }

    /**
     * 验证F码
     * @param int $goods_commonid
     * @param string $fcode
     * @return array
     */
    public function checkFcode($goods_goodid, $fcode)
    {
        $fcode_info = model('goodsfcode')->getGoodsfcode(array(
            'goods_commonid' => $goods_goodid, 'goodsfcode_code' => $fcode,
            'goodsfcode_state' => 0
        ));
        if ($fcode_info) {
            return ds_callback(true, '', $fcode_info);
        } else {
            return ds_callback(false, 'F码错误');
        }
    }

    /**
     * 订单生成前的表单验证与处理
     *
     */
    private function _createProjectOrderStep1()
    {
        $post = $this->_post_data;

        if ($post['order_type'] == '2') {
            //取项目定制商品获取 商品ID和购买数量
            $input_buy_items = $this->_prodectItems($post['prodect_id']);
        } else {
            //取得商品ID和购买数量
            $input_buy_items = $this->_parseItems($post['cart_id']);
        }

        if (empty($input_buy_items)) {
            exception('所购商品无效');
        }


        //验证收货地址
        $input_address_id = intval($post['address_id']);
        if ($input_address_id <= 0) {
            exception('请选择收货地址');
        } else {
            $input_address_info = model('address')->getAddressInfo(array('address_id' => $input_address_id));
            if ($input_address_info['member_id'] != $this->_member_info['member_id']) {
                exception('请选择收货地址');
            }
        }

        //收货地址城市编号
        $input_city_id = intval($input_address_info['city_id']);


        //是否支持货到付款

        if (!from_api()) {
            $input_if_offpay = $this->buyDecrypt($post['offpay_hash'], $this->_member_info['member_id']);
            if (!in_array($input_if_offpay, array('allow_offpay', 'deny_offpay'))) {
                exception('订单保存出现异常[货到付款验证错误]，请重试');
            }
            $input_if_offpay = ($input_if_offpay == 'allow_offpay') ? true : false;

            // 是否支持货到付款 具体到各个店铺
            $input_if_offpay_batch = $this->buyDecrypt($post['offpay_hash_batch'], $this->_member_info['member_id']);
            if (!is_array($input_if_offpay_batch)) {
                exception('订单保存出现异常[部分店铺付款方式出现异常]，请重试');
            }
            $this->_order_data['input_if_offpay'] = $input_if_offpay;
            $this->_order_data['input_if_offpay_batch'] = $input_if_offpay_batch;
        }
        //付款方式:在线支付/货到付款(online/offline)
        if (!in_array($post['pay_name'], array('online', 'offline'))) {
            exception('付款方式错误，请重新选择');
        }
        $input_pay_name = $post['pay_name'];

        //验证发票信息
        $input_invoice_info = array();
        if (!empty($post['invoice_id'])) {
            $input_invoice_id = intval($post['invoice_id']);
            if ($input_invoice_id > 0) {
                $input_invoice_info = model('invoice')->getInvoiceInfo(array('invoice_id' => $input_invoice_id));
                if ($input_invoice_info['member_id'] != $this->_member_info['member_id']) {
                    exception('请正确填写发票信息');
                }
            }
        }

        //验证代金券
        $input_voucher_list = array();
        if (!empty($post['voucher']) && is_array($post['voucher'])) {
            foreach ($post['voucher'] as $store_id => $voucher) {
                if (preg_match_all('/^(\d+)\|(\d+)\|([\d.]+)$/', $voucher, $matchs)) {
                    if (floatval($matchs[3][0]) > 0) {
                        $input_voucher_list[$store_id]['vouchertemplate_id'] = $matchs[1][0];
                        $input_voucher_list[$store_id]['voucher_price'] = $matchs[3][0];
                    }
                }
            }
        }

        //保存数据
        $this->_order_data['input_buy_items'] = $input_buy_items;
        $this->_order_data['input_city_id'] = $input_city_id;
        $this->_order_data['input_pay_name'] = $input_pay_name;
        $this->_order_data['input_address_info'] = $input_address_info;
        $this->_order_data['input_invoice_info'] = $input_invoice_info;
        $this->_order_data['input_voucher_list'] = $input_voucher_list;
        $this->_order_data['order_from'] = $post['order_from'] == 2 ? 2 : 1;
    }

    /**
     * 订单生成前的表单验证与处理
     *
     */
    private function _createOrderStep1()
    {

        $post = $this->_post_data;

        //取得商品ID和购买数量
        $input_buy_items = $this->_parseItems($post['cart_id']);
        //p($input_buy_items);die;   #[256] => 2

        if (empty($input_buy_items)) {
            exception('所购商品无效');
        }


        //验证收货地址
        $input_address_id = intval($post['address_id']);
        if ($input_address_id <= 0) {
            exception('请选择收货地址');
        } else {
            $input_address_info = model('address')->getAddressInfo(array('address_id' => $input_address_id));
            /*  if ($input_address_info['member_id'] != $this->_member_info['member_id']) {
                  exception('请选择收货地址');
              }*/
        }

        //收货地址城市编号
        $input_city_id = intval($input_address_info['city_id']);

        //是否开增值税发票
        $input_if_vat = $this->buyDecrypt($post['vat_hash'], $this->_member_info['member_id']);
        if (!in_array($input_if_vat, array('allow_vat', 'deny_vat'))) {
            exception('订单保存出现异常[值税发票出现错误]，请重试');
        }
        $input_if_vat = ($input_if_vat == 'allow_vat') ? true : false;

        //是否支持货到付款

        if (!from_api()) {
            $input_if_offpay = $this->buyDecrypt($post['offpay_hash'], $this->_member_info['member_id']);
            if (!in_array($input_if_offpay, array('allow_offpay', 'deny_offpay'))) {
                exception('订单保存出现异常[货到付款验证错误]，请重试');
            }
            $input_if_offpay = ($input_if_offpay == 'allow_offpay') ? true : false;

            // 是否支持货到付款 具体到各个店铺
            $input_if_offpay_batch = $this->buyDecrypt($post['offpay_hash_batch'], $this->_member_info['member_id']);
            if (!is_array($input_if_offpay_batch)) {
                exception('订单保存出现异常[部分店铺付款方式出现异常]，请重试');
            }
            $this->_order_data['input_if_offpay'] = $input_if_offpay;
            $this->_order_data['input_if_offpay_batch'] = $input_if_offpay_batch;
        }
        //付款方式:在线支付/货到付款(online/offline)
        if (!in_array($post['pay_name'], array('online', 'offline'))) {
            exception('付款方式错误，请重新选择');
        }
        $input_pay_name = $post['pay_name'];

        //验证发票信息
        $input_invoice_info = array();
        if (!empty($post['invoice_id'])) {
            $input_invoice_id = intval($post['invoice_id']);
            if ($input_invoice_id > 0) {
                $input_invoice_info = model('invoice')->getInvoiceInfo(array('invoice_id' => $input_invoice_id));
                if ($input_invoice_info['member_id'] != $this->_member_info['member_id']) {
                    exception('请正确填写发票信息');
                }
            }
        }

        //验证代金券
        $input_voucher_list = array();
        if (!empty($post['voucher']) && is_array($post['voucher'])) {
            foreach ($post['voucher'] as $store_id => $voucher) {
                if (preg_match_all('/^(\d+)\|(\d+)\|([\d.]+)$/', $voucher, $matchs)) {
                    if (floatval($matchs[3][0]) > 0) {
                        $input_voucher_list[$store_id]['vouchertemplate_id'] = $matchs[1][0];
                        $input_voucher_list[$store_id]['voucher_price'] = $matchs[3][0];
                    }
                }
            }
        }

        //保存数据
        $this->_order_data['input_buy_items'] = $input_buy_items;
        $this->_order_data['input_city_id'] = $input_city_id;
        $this->_order_data['input_pay_name'] = $input_pay_name;
        $this->_order_data['input_pay_message'] = $post['pay_message'];
        $this->_order_data['input_address_info'] = $input_address_info;
        $this->_order_data['input_invoice_info'] = $input_invoice_info;
        $this->_order_data['input_voucher_list'] = $input_voucher_list;
        $this->_order_data['order_from'] = $post['order_from'] == 2 ? 2 : 1;
    }

    /**
     * 得到购买商品信息
     *
     */
    private function _createOrderStep2()
    {

        $post = $this->_post_data;

        $type_array = json_decode(htmlspecialchars_decode($post['type_array']), true);
        $input_buy_items = $this->_order_data['input_buy_items'];

        //获取用户地址的所在位置的区code
        $address_id = intval($post['address_id']);
        $address_info = db('address')->where(['address_id' => $address_id])->find();

        if ($post['ifcart']) {
            //购物车列表
            $cart_model = model('cart');
            $condition = array(
                'cart_id' => array('in', array_keys($input_buy_items)), 'buyer_id' => $this->_member_info['member_id']
            );
            $cart_list = $cart_model->getCartList('db', $condition);

            //购物车列表 [得到最新商品属性及促销信息]
            $cart_list = $this->_logic_buy_1->getGoodsCartList($cart_list);


            //商品列表 [优惠套装子商品与普通商品同级罗列]
            $goods_list = $this->_getGoodsList($cart_list);


            //如果有满赠 (重新组装商品列表)
            if (!empty($post['deduction_ids'])) {
                //找到商品id
                $rule_info = db('pmansongrule')->where(['mansongrule_id' => $post['deduction_ids'][0]])->find();
                if (!empty($rule_info['goods_id'])) {
                    $full_goods_info = $this->_logic_buy_1->getCartGoodsOnlineInfo($rule_info['goods_id'], intval($rule_info['goods_num']));
                    $full_goods_info['is_full'] = 1; #是否为赠品
                    array_push($goods_list, $full_goods_info);

                    $new_goods_info = $this->_logic_buy_1->getGoodsOnlineInfo($rule_info['goods_id'], intval($rule_info['goods_num']), array(), $this->_member_info['member_id']);
                    $new_goods_info['address_id'] = $address_id;
                    $new_goods_info['cart_price'] = $rule_info['new_price'];
                    $new_goods_info['original_price'] = $rule_info['new_price'];
                    $new_goods_info['is_full'] = 1; #是否为赠品
                    array_push($cart_list, $new_goods_info);
                }
            }

            //以店铺下标归类
            $store_cart_list = $this->_getStoreCartList($cart_list);

            $not_array = [];
            foreach ($goods_list as $k => $v) {
                if (!strstr($v['area'], (string)$address_info['area_id'])) {
                    $not_array[] = $v['goods_name'];
                }
            }
            if (!empty($not_array)) {
                json_fail_return('商品不再销售区域', $not_array);
            }
            $address_area_id = $address_info['area_id'];  #地址的区id


        } else {

            //来源于直接购买
            $goods_id = key($input_buy_items);
            $quantity = current($input_buy_items);

            //额外数据用来处理拼团等其他活动
            $pintuan_id = isset($post['pintuan_id']) ? intval($post['pintuan_id']) : 0;
            $extra = array();
            if ($pintuan_id > 0) {
                $extra['pintuan_id'] = $pintuan_id; #拼团ID
                #是否为开团订单
                $extra['pintuangroup_id'] = empty(input('param.pintuangroup_id')) ? 0 : intval(input('param.pintuangroup_id'));
            }
            $bargainorder_id = isset($post['bargainorder_id']) ? intval($post['bargainorder_id']) : 0;
            if ($bargainorder_id > 0) {
                $extra['bargainorder_id'] = $bargainorder_id; #砍价ID
            }

            //商品信息[得到最新商品属性及促销信息]
            $goods_info = $this->_logic_buy_1->getGoodsOnlineInfo($goods_id, intval($quantity), $extra, $this->_member_info['member_id']);
            if (empty($goods_info)) {
                exception('商品已下架或不存在');
            }

            $not_array = [];
            if (!strstr($goods_info['area'], (string)$address_info['area_id'])) {
                $not_array[] = $goods_info['goods_name'];
            }
            if (!empty($not_array)) {
                json_fail_return('商品不再销售区域', $not_array);
            }

            #计算安装费 start 找到地址id 
            $input_address_id = intval($post['address_id']);
            if ($input_address_id) {
                $address_info = db('address')->where(['address_id' => $input_address_id])->find();
                if (!$address_info) {
                    return json_fail_return('地址不存在');
                }
                $address_area_id = $address_info['area_id'];  #地址的区id
            } else {
                $address_area_id = 0; #地址的区id
            }
            if ($post['is_install'] == 1) {
                if ($goods_info['install_money']) {
                    $sum_install_money = get_install_money($address_area_id, (float)$goods_info['install_money']);
                } else {
                    $sum_install_money = 0;
                }
            }
            # end

            //判断是否有满赠的商品
            $full_goods_info = [];
            if (!empty($post['deduction_ids'])) {
                //找到商品id
                $rule_info = db('pmansongrule')->where(['mansongrule_id' => $post['deduction_ids'][0]])->find();
                if (!empty($rule_info['goods_id'])) {
                    $full_goods_info = $this->_logic_buy_1->getGoodsOnlineInfo($rule_info['goods_id'], intval($rule_info['goods_num']), $extra, $this->_member_info['member_id']);
                    $full_goods_info['goods_price'] = 0;
                    $full_goods_info['is_full'] = 1; #是否为赠品
                    #组装新的数组，根据店铺id来区分
                    $new_goods_info = [];
                    array_push($new_goods_info, $goods_info, $full_goods_info);

                    //根据下标区分
                    $store_cart_list = $this->_getFullStoreCartList($new_goods_info);
                    //商品列表 
                    $goods_list = $this->_getFullGoodsList($new_goods_info, $post);
                    if ($post['is_install'] == 1) {
                        $goods_info['is_install'] = 1;
                    } else {
                        $goods_info['is_install'] = 0;
                    }
                }
            }
            //进一步处理数组
            $store_cart_list = array();
            $goods_list = array();
            $goods_list[0] = $store_cart_list[$goods_info['store_id']][0] = $goods_info;
            if ($post['is_install'] == 1) {
                $store_cart_list[$goods_info['store_id']][0]['install_money'] = $sum_install_money;
                $store_cart_list[$goods_info['store_id']][0]['is_install'] = 1;
                $goods_info['is_install'] = 1;
            } else {
                $store_cart_list[$goods_info['store_id']][0]['install_money'] = 0;
                $store_cart_list[$goods_info['store_id']][0]['is_install'] = 0;
                $goods_info['is_install'] = 0;
            }

        }

        //F码验证
        $goodsfcode_id = '';
        if (!empty($post['fcode'])) {
            $goodsfcode_id = $this->_checkFcode($goods_list, $post['fcode']);
            if (!$goodsfcode_id) {
                exception('F码商品验证错误');
            }
        }
        #需要修改
        foreach ($goods_list as $key => $val) {
            foreach ($type_array as $ke => $va) {
                foreach ($va as $kk => $vv) {
                    if ($vv['goods_id'] == $val['goods_id'])
                        $goods_list[$key]['is_home'] = $vv['is_home'];
                }
            }
        }


        //保存数据
        $this->_order_data['type_array'] = $type_array;
        $this->_order_data['goods_list'] = $goods_list;
        $this->_order_data['store_cart_list'] = $store_cart_list;
        $this->_order_data['goodsfcode_id'] = $goodsfcode_id;
        $this->_order_data['address_area_id'] = $address_area_id;
    }

    /**
     * 得到购买相关金额计算等信息
     *
     */
    private function _createOrderStep3()
    {

        $post = $this->_post_data;
        $goods_list = $this->_order_data['goods_list'];

        //p($goods_list);die;
        $store_cart_list = $this->_order_data['store_cart_list'];
        $input_voucher_list = $this->_order_data['input_voucher_list'];
        $input_city_id = $this->_order_data['input_city_id'];


        // 根据店铺区分 再重新计算出商品价格  ---------------------------  在这里面计算出安装费
        // list($store_cart_list, $store_goods_total, $store_goods_discount) = $this->_logic_buy_1->calcCartList($store_cart_list, $post['ifcart']);
        list($store_cart_list, $store_goods_total, $store_goods_discount) = $this->_logic_buy_1->calcCreateCartList($store_cart_list, $post['ifcart'], $post['is_install'], $post['address_id']);

        //zjw 判断是走折扣的金额 还是没折扣的金额
        $new_prcie = $store_goods_total;

        //取得店铺优惠 - 满即送(赠品列表，店铺满送规则列表) 34000
        list($store_premiums_list, $store_mansong_rule_list) = $this->_logic_buy_1->getMansongruleCartListByTotal($new_prcie, $goods_list);

        //重新计算店铺扣除满即送后商品实际支付金额  （应该没用，如果报错再放开）
        // $store_final_goods_total = $this->_logic_buy_1->reCalcGoodsTotal($store_goods_total, $store_mansong_rule_list, 'mansong');

        //商品总价  +  安装费  ------------------------------------------ZJW
        $store_final_goods_total = $store_goods_total;

        //得到有效的代金券
        $input_voucher_list = $this->_logic_buy_1->reParseVoucherList($input_voucher_list, $store_goods_total, $this->_member_info['member_id']);

        //计算每个店铺(所有店铺级优惠活动)总共优惠多少
        $store_promotion_total = $this->_logic_buy_1->getStorePromotionTotal($store_goods_total, $store_final_goods_total);

        //计算每个店铺运费
        $address_area_id = $this->_order_data['address_area_id'];
        if (from_api()) {
            $json_ = crypt_de(input('post.freight_list_hash'));
            $goods_waybill = json_to_array($json_);
            if (!$json_ || !$goods_waybill) {
                json_fail_return('运费信息验证失败');
                die;
            }
            $freight_list = GoodsService::getInstance()->calculateFreight(array(), $address_area_id, json_decode(htmlspecialchars_decode(input('post.type_array')), true));

            $store_freight_total = array();

            foreach ($freight_list as $k => $v) {
                if ((string)$k == "sum_freight") {
                    continue;
                }
                $store_freight_total[$v['shop_id']] = $v['shop_sum_freight'];
            }
        } else {
            list($need_calc_sid_list, $cancel_calc_sid_list) = $this->_logic_buy_1->getStoreFreightDescList($store_final_goods_total);
            $freight_list = $this->_logic_buy_1->getStoreFreightList($goods_list, array_keys($cancel_calc_sid_list));


            $store_freight_total = $this->_logic_buy_1->calcStoreFreight($freight_list, $input_city_id);
            if (empty($store_freight_total)) {
                exception('抱歉，商品在所在地区无货');
            }
        }

        //计算店铺最终订单实际支付金额    34201.47     (商品总价 + 安装费 + 运费) == 订单总价 --------------------------------ZJW
        $store_final_order_total = $this->_logic_buy_1->reCalcGoodsTotal($store_final_goods_total, $store_freight_total, 'freight');

        //p($store_final_order_total);die;
        //计算店铺分类佣金[改由任务计划]
        $store_gc_id_commis_rate_list = model('storebindclass')->getStoreGcidCommisRateList($goods_list);

        //将赠品追加到购买列表(如果库存0，则不送赠品)
        $append_premiums_to_cart_list = $this->_logic_buy_1->appendPremiumsToCartList($store_cart_list, $store_premiums_list, $store_mansong_rule_list, $this->_member_info['member_id']);
        if ($append_premiums_to_cart_list === false) {
            exception('暂时无货');
        } else {
            list($store_cart_list, $goods_buy_quantity, $store_mansong_rule_list) = $append_premiums_to_cart_list;
        }


        // $this->_order_data['total'] = $total;
        $this->_order_data['store_goods_total'] = $store_goods_total;

        //zjw  差价
        $this->_order_data['store_goods_discount'] = $store_goods_discount;


        $this->_order_data['store_final_order_total'] = $store_final_order_total; #订单总价
        $this->_order_data['store_freight_total'] = $store_freight_total; #运费总价

        $this->_order_data['store_promotion_total'] = $store_promotion_total;
        $this->_order_data['store_final_goods_total'] = $store_final_goods_total;

        $this->_order_data['store_gc_id_commis_rate_list'] = $store_gc_id_commis_rate_list;
        $this->_order_data['store_mansong_rule_list'] = $store_mansong_rule_list;
        $this->_order_data['store_cart_list'] = $store_cart_list;
        $this->_order_data['goods_buy_quantity'] = $goods_buy_quantity;
        $this->_order_data['input_voucher_list'] = $input_voucher_list;
    }

    /**
     * 生成订单
     * @param array $input
     * @return array array(支付单sn,订单列表) ,$voucher_id
     * @throws Exception
     */
    private function _createOrderStep4($is_integrals, $amount_reduction, $voucher_id, $deduction_ids)
    {
        extract($this->_order_data);
        $post = $this->_post_data;
        $member_id = $this->_member_info['member_id'];
        $member_name = $this->_member_info['member_name'];
        $member_email = $this->_member_info['member_email'];
        $type_array = $this->_order_data['type_array'];

        //是否使用积分  0—未使用 1—使用
        $is_integral = $is_integrals;

        //如果用户使用优惠劵了  获取优惠劵的面额 
        if (!empty($voucher_id)) {
            //获取优惠劵信息
            $voucher_info = db('voucher')->where(['voucher_id' => $voucher_id])->find();
            $voucher_price = $voucher_info['voucher_price'];
            //使用完改变优惠劵状态
            $voucher_list = db('voucher_collection')->where(['member_id' => $member_id, 'voucher_id' => $voucher_id, 'is_used' => 1, 'is_send_del' => 0])->select();
            db('voucher_collection')->where(['id' => $voucher_list[0]['id']])->update(['is_used' => 2]);
        } else {
            $voucher_price = 0;
        }


        //满减 立减了多少钱
        if (!empty($amount_reduction)) {
            $amount_reduction = $amount_reduction;
        } else {
            $amount_reduction = 0;
        }

        //获取满减的总金额
        $total_deduction = []; #总价   如果有满赠，就是 减的金额+平台设置满赠的商品价格
        $deduction_text = [];  #Wenben
        $gift_price = 0; #满赠金额
        $store_deduction_price = '';
        if (!empty($deduction_ids)) {
            foreach ($deduction_ids as $k => $v) {
                $mansong_info = db('pmansongrule')->where(['mansongrule_id' => $v])->find();
                if (!empty($mansong_info['goods_id'])) {
                    $gift_price += $mansong_info['new_price'];
                }
                $total_deduction[] = ($mansong_info['mansongrule_discount'] + $mansong_info['new_price']);
                $deduction_text[] = $mansong_info['mansongrule_discount'] . '元+' . $gift_price . '元商品';
                $store_deduction_price = $v . ',' . $amount_reduction;
            }
        }

        //获取订单的总价（商品的价格+运费）
        $order_count = array_values($store_final_order_total); #将不同供应商下的价格都求出来
        $order_count_price = array_sum($order_count); #求出所有商品的总价（包括运费）

        $integral_price = 0;  #计算使用积分的金额
        $fina_integral = 0; #最终使用的积分
        //是否使用积分抵扣
        if ($is_integral == 1) {
            //获取比例  订单总金额/比例==商品总价转换为积分（积分）
            //现有积分 > 商品总价转换为积分（积分） -->(使用商品总价转换为积分（积分）)
            //现有积分 < 商品总价转换为积分（积分） -->(现有积分)
            //商品价格 - 上面的积分*比例

            //用户详情
            $member_info = db('member')->where(['member_id' => $member_id])->find();
            //积分数量
            $integral_ratio = db('config')->where('code', 'integral_ratio')->find();
            //金额数量
            $price_ratio = db('config')->where('code', 'price_ratio')->find();
            //比例
            $bili = $price_ratio['value'] / $integral_ratio['value'];

            //(如果当前的商品都使用积分，计算出用多少积分)获取商品总价可以转化多少积分
            $count_integral = ($order_count_price - $voucher_price) / $bili;

            if ($member_info['member_points'] > $count_integral) {
                $fina_integral = $count_integral;
            } else {
                $fina_integral = $member_info['member_points'];
            }

            //算上抵扣积分之后的总价格  总价格（商品总价格+运费）- 积分抵扣的金额 - 满减的金额-优惠劵
            $integral_price = ($order_count_price - $voucher_price) - ($fina_integral * $bili) - $amount_reduction;

            //下完单减积分
            $update_integral = $member_info['member_points'] - $fina_integral;
            db('member')->where(['member_id' => $member_id])->update(['member_points' => $update_integral]);

            #生成积分消费日志
            $points_info = [
                'pl_memberid' => $member_id,
                'pl_membername' => $member_name,
                'pl_points' => '-' . $fina_integral,
                'pl_addtime' => time(),
                'pl_desc' => '购买商品',
                'pl_stage' => 'order',
                'pl_balance' => $update_integral
            ];
            db('pointslog')->insertGetId($points_info);
        } else {
            // 不使用   总价格（商品总价格+运费） - 满减的金额
            $integral_price = ($order_count_price - $voucher_price) - $amount_reduction;
        }

        $order_model = new \app\common\model\Order();
        $stat_model = new \app\common\model\Stat();

        //存储生成的订单数据
        $order_list = array();
        //存储通知信息
        $notice_list = array();
        //每个店铺订单是货到付款还是线上支付,店铺ID=>付款方式[在线支付/货到付款]
        $store_pay_type_list = $this->_logic_buy_1->getStorePayTypeList(array_keys($store_cart_list), false, $input_pay_name);

        $yys_id = get_parent_store_id();
        $yys_info = db('store')->where('store_id', $yys_id)->find();

        foreach ($store_pay_type_list as $k => &$v) {
            if (empty($input_if_offpay_batch[$k]))
                $v = 'online';
        }
        $pay_sn = makePaySn($member_id);
        $order_pay = array();
        $order_pay['pay_sn'] = $pay_sn;
        $order_pay['buyer_id'] = $member_id;
        $order_pay_id = $order_model->addOrderpay($order_pay);
        if (!$order_pay_id) {
            exception('订单保存失败[未生成支付单]');
        }

        $sellerModel = new Seller();
        //p($yys_id);die;           // TODO
        // p($input_address_info);die;
        //收货人信息
        list($reciver_info, $reciver_name) = $this->_logic_buy_1->getReciverAddr($input_address_info);

        //订单的总额
        $place_price = 0;
        //商品的件数
        $merchandise = 0;

        //获取到每个订单平分的积分数
        $store_integra_price = $fina_integral / count($store_cart_list);

        //获取到每个订单平分的优惠劵金额
        $store_voucher_price = $voucher_price / count($store_cart_list);


        $order_freight = array_values($store_freight_total);

        foreach ($store_cart_list as $store_id => $goods_list) {
            #获取店铺信息
            $store_info = db('store')->where(['store_id' => $store_id])->find();

            //订单的总额   $store_final_order_total[$store_id]==>(商品价格+运费)
            $place_price += ($store_final_order_total[$store_id] - $order_freight[0]);

            // //如果有优惠劵使用
            // if (!empty($voucher_id)) {
            //     //下完单改变状态
            //     db('voucher_collection')->where(['member_id' => $member_id])->update(['is_used' => 2, 'used_time' => time()]);
            // }

            #生成店铺下单金额统计（生成商城订单统计--收入统计的列表）
            $store_data = [
                'ob_order_totals' => $integral_price,
                'ob_shipping_totals' => $order_freight[0],
                'ob_store_id' => $store_id,
                'ob_store_name' => $store_info['store_name'],
            ];
            $stat_model->generateStoreMall($store_data);


            //取得本店优惠额度(后面用来计算每件商品实际支付金额，结算需要)
            $promotion_total = !empty($store_promotion_total[$store_id]) ? $store_promotion_total[$store_id] : 0;

            //本店总的优惠比例,保留3位小数
            $should_goods_total = $store_final_order_total[$store_id] - $order_freight[0] + $promotion_total;
            // $promotion_rate = abs(number_format($promotion_total / $should_goods_total, 5));
            $promotion_rate = 0;
            if ($promotion_rate <= 1) {
                $promotion_rate = floatval(substr($promotion_rate, 0, 5));
            } else {
                $promotion_rate = 0;
            }
            //每种商品的优惠金额累加保存入 $promotion_sum
            $promotion_sum = 0;

            $order = array();
            $order_common = array();
            $order_goods = array();
            $app_order = array();

            $order['order_sn'] = $this->_logic_buy_1->makeOrderSn($order_pay_id);
            $order['pay_sn'] = $pay_sn;
            $order['store_id'] = $store_id;
            $order['store_name'] = $goods_list[0]['store_name'];
            $order['buyer_id'] = $member_id;
            $order['buyer_name'] = $member_name;
            $order['buyer_email'] = $member_email;
            $order['add_time'] = TIMESTAMP;
            $order['payment_code'] = $store_pay_type_list[$store_id];
            $order['order_state'] = $store_pay_type_list[$store_id] == 'online' ? ORDER_STATE_NEW : ORDER_STATE_PAY;
            //订单总价格
            // $order['order_amount'] = $store_final_order_total[$store_id];
            $order['order_amount'] = $integral_price;
            //运费$store_freight_total
            // $order['shipping_fee'] = $order_freight[0];
            $order['shipping_fee'] = $store_freight_total[$store_id];
            //商品价格
            // $order['goods_amount'] = $order['order_amount'] - $order['shipping_fee'];
            $order['goods_amount'] = $store_final_order_total[$store_id] - $order['shipping_fee'];
            $order['order_from'] = $order_from;
            $order['yys_id'] = $yys_id;
            $order['yys_name'] = $yys_info['store_name'];
            $order['order_integral'] = $store_integra_price; #每个订单平分的积分
            $order['order_voucher'] = $store_voucher_price; #每个订单平分的优惠劵

            $order['avg_total_deduction'] = $store_deduction_price; #每个订单平分的满减

            //如果支持方式为空时，默认为货到付款
            if ($order['payment_code'] == "") {
                $order['payment_code'] = "offline";
            }

            #存入地址信息 及 订单地址的钱
            if (isset($post['area_content']) && $post['area_content'] != '') {
                $area_content = json_decode(htmlspecialchars_decode($post['area_content']), true);
                if ($area_content) {
                    foreach ($area_content as $k => $v) {

                        if ($v['shop_id'] == $store_id) {
                            $order['shipping_fee'] = $v['shop_sum_freight'];
                            $order['freight_content'] = json_encode($v['goods_info']);
                        }
                    }
                } else {
                    $order['shipping_fee'] = 0;
                    $order['freight_content'] = '';
                }
            } else {
                $order['shipping_fee'] = 0;
                $order['freight_content'] = '';
            }

            $order_id = $order_model->addOrder($order);
            if (!$order_id) {
                exception('订单保存失败[未生成订单数据]');
            }
            $order['order_id'] = $order_id;
            $order_list[$order_id] = $order;

            $order_common['order_id'] = $order_id;
            $order_common['store_id'] = $store_id;
            $order_common['order_message'] = $input_pay_message[$store_id];

            //代金券
            if (isset($input_voucher_list[$store_id])) {
                $order_common['voucher_price'] = $input_voucher_list[$store_id]['voucher_price'];
                $order_common['voucher_code'] = $input_voucher_list[$store_id]['voucher_code'];
            }

            $order_common['reciver_info'] = $reciver_info;
            $order_common['reciver_name'] = $reciver_name;
            $order_common['reciver_city_id'] = $input_city_id;


            //发票信息
            $order_common['invoice_info'] = $this->_logic_buy_1->createInvoiceData($input_invoice_info);
            //保存促销信息
            if (isset($store_mansong_rule_list[$store_id])) {
                $order_common['promotion_info'] = addslashes($store_mansong_rule_list[$store_id]['desc']);
            }

            $order_id = $order_model->addOrdercommon($order_common);


            if (!$order_id) {
                exception('订单保存失败[未生成订单扩展数据]');
            }

            #生成订单缓存表，用于统计订单
            $order_cache = db('order')->where(['order_id' => $order_id])->find();
            $res_cache = [
                'order_id' => $order_id,
                'order_sn' => $order_cache['order_sn'],
                'order_type' => 1,
                'order_add_time' => time(),
                'payment_code' => 1,
                'order_amount' => $order_cache['order_amount'],
                'shipping_fee' => $order_cache['shipping_fee'],
                'evaluation_state' => $order_cache['evaluation_state'],
                'order_state' => $order_cache['order_state'],
                'refund_state' => $order_cache['refund_state'],
                'refund_amount' => $order_cache['refund_amount'],
                'order_from' => $order_cache['order_from'],
                'order_isvalid' => 1,
                'store_id' => $store_id,
                'store_name' => $store_info['store_name'],
                'buyer_id' => $member_id,
                'buyer_name' => $member_name,
            ];
            db('statorder')->insertGetId($res_cache);

            #下单生成供应商  的交易金额和收益金额
            $supplie_data = [
                'order_id' => $order_id,
                'order_sn' => $order_cache['order_sn'],
                'member_id' => $member_id,
                'member_name' => $member_name,
                'supplier_total' => $store_final_order_total[$store_id], #交易金额
                'supplier_profit' => $integral_price,
                'store_id' => $store_id,
                'store_name' => $store_info['store_name'],
                'time' => time()
            ];
            $stat_model->generateSupplie($supplie_data);

            #下单生成运营商  的交易金额和收益金额
            $stat_data = [
                'order_id' => $order_id,
                'order_sn' => $order_cache['order_sn'],
                'member_id' => $member_id,
                'member_name' => $member_name,
                'statstore_total' => $store_final_order_total[$store_id], #交易金额
                'statstore_profit' => $integral_price,
                'store_id' => $yys_id,
                'store_name' => $yys_info['store_name'],
                'time' => time()
            ];
            $stat_model->generateStat($stat_data);

            //生成order_goods订单商品数据
            $count = 0; #返回的总积分
            $markup_price = 0; #计算每个商品的加价金额，用于统计商城的总计收入
            $i = 0;
            $order_count_discount = 0; #每个订单的总折扣费用
            $order_count_door = 0; #每个订单总的安装费用
            $supplier_price = 0; #给到供应商的总价格
            foreach ($goods_list as $goods_info) {
                $merchandise++;
                if (!$goods_info['state'] || !$goods_info['storage_state']) {
                    exception('部分商品已经下架或库存不足，请重新选择');
                }
                //判断当前商品是否参与折扣
                $xianshi_info = db('pxianshigoods')->where(['goods_id' => $goods_info['goods_id']])->find();
                //判断折扣活动是否异常
                $parms = [
                    'xianshi_id' => $xianshi_info['xianshi_id'],
                    'xianshi_end_time' => ['gt', time()]
                ];
                $xianshi = db('pxianshi')->where($parms)->find();

                if (!intval($goods_info['bl_id'])) {
                    // if (!empty($goods_info['xianshi_info'])) {

                    //判断折扣
                    if (!empty($xianshi)) {
                        #判断运营商的类型
                        $supplier_type = get_supplier_type();
                        $goods_total_sum = 0; #商品的总价
                        if ($supplier_type == 1) {
                            #加价157.2
                            $yys_id = get_parent_store_id();

                            $y_goods_info = db('y_goods')->where('goods_id', $goods_info['goods_id'])->where('store_id', $yys_id)->find();


                            $goods_total_sum = ($goods_info['gu_final_price'] + $y_goods_info['price']) * $goods_info['goods_num'];
                        } else {
                            #提成
                            $goods_total_sum = $goods_info['ti_final_price'] * $goods_info['goods_num'];
                        }
                        // $xianshi_info = db('pxianshi')->where(['xianshi_id' => $goods_info['xianshi_info']['xianshi_id']])->find();
                        // #商品的总价 - 折扣以后的商品总价 = 折扣多少钱
                        // $goods_discount_price = $goods_total_sum * ($xianshi_info['discount_rate'] / 100);
                        // $order_goods[$i]['is_discount'] = 1;
                        // $order_goods[$i]['discount_id'] = $goods_info['xianshi_info']['xianshi_id'];
                        // $order_goods[$i]['discount_price'] = $goods_discount_price;
                        #商品的总价 - 折扣以后的商品总价 = 折扣多少钱
                        $goods_discount_price = $goods_total_sum * ($xianshi['discount_rate'] / 100);
                        $order_goods[$i]['is_discount'] = 1;
                        $order_goods[$i]['discount_id'] = $xianshi['xianshi_id'];
                        $order_goods[$i]['discount_price'] = $goods_discount_price;

                        #将每个商品折扣金额、安装费，累加到订单里面
                        $order_count_discount += $goods_discount_price;

                        db('order')->where(['order_id' => $order_id])->update(['order_count_discount' => $order_count_discount]);
                    } else {
                        $order_goods[$i]['is_discount'] = 0;
                        $order_goods[$i]['discount_id'] = 0;
                        $order_goods[$i]['discount_price'] = 0;
                    }


                    //如果当前商品有安装费，入库
                    // if ($goods_info['is_install'] == 1) {
                    if ($goods_info['install_money'] > 0) {

                        $order_goods[$i]['is_goods_door'] = 1;
                        $order_goods[$i]['door_price'] = $goods_info['install_money'];
                        $order_goods[$i]['door_count_price'] = $goods_info['install_money'] * $goods_info['goods_num'];

                        #规格拼接安装费
                        if($goods_info['spec_values']){
                            $goods_info['spec_values'] = '含有安装费;'.$goods_info['spec_values'];
                        }else{
                            $goods_info['spec_values'] = '含有安装费';
                        }


                        $order_count_door += $order_goods[$i]['door_count_price'];
                        db('order')->where(['order_id' => $order_id])->update(['order_count_door' => $order_count_door]);
                    } else {
                        $order_goods[$i]['is_goods_door'] = 0;
                        $order_goods[$i]['door_price'] = 0;
                        $order_goods[$i]['door_count_price'] = 0;
                    }

                    //如果不是优惠套装
                    $order_goods[$i]['order_id'] = $order_id;
                    $order_goods[$i]['goods_id'] = $goods_info['goods_id'];
                    $order_goods[$i]['store_id'] = $store_id;
                    $order_goods[$i]['goods_name'] = $goods_info['goods_name'];

                    //需要判断是否是购物车来的(因为有折扣的商品在购物车的时候就已经算完折扣后的金额了。)
                    $order_goods[$i]['goods_price'] = $goods_info['goods_price'];
                    // if ($post['ifcart'] == 0) {
                    //     //直接购买，有折扣的话，需要算出商品折扣后的金额
                    //     if(!empty($xianshi)){
                    //         $xianshi_info = db('pxianshi')->where(['xianshi_id' => $xianshi['xianshi_id']])->find();
                    //         $order_goods[$i]['goods_price'] = $goods_info['goods_price'] - ($goods_info['goods_price'] * ($xianshi_info['discount_rate'] / 100));
                    //     }
                    // }

                    $order_goods[$i]['goods_num'] = $goods_info['goods_num'];
                    #shen
                    $order_goods[$i]['spec_values'] = $goods_info['spec_values'];

                    foreach ($type_array[$store_id] as $kkk => $vvv) {
                        if ($goods_info['goods_id'] == $type_array[$store_id][$kkk]['goods_id']) {
                            $order_goods[$i]['is_home'] = $vvv['is_home'];
                        }
                    }


                    $info = db('goods')->where(['goods_id' => $goods_info['goods_id']])->find();

                    $count += $info['score'];
                    $markup_price += $info['markup_price'];

                    $order_goods[$i]['goods_image'] = $goods_info['goods_image'];
                    $order_goods[$i]['buyer_id'] = $member_id;
                    $order_goods[$i]['goods_original_price'] = $info['goods_price'];  #供应商给平台的价格（展示在供应商）

                    $supplier_type = get_supplier_type(); #运营商类型
                    $goods_sale_price = 0; #获取运营商卖给客户的单价
                    if ($supplier_type == 1) {
                        #加价157.2
                        $yys_id = get_parent_store_id();

                        $y_goods_info = db('y_goods')->where('goods_id', $goods_info['goods_id'])->where('store_id', $yys_id)->find();
                        $y_goods_price = empty($y_goods_info['price']) ? 0 : $y_goods_info['price'];

                        $goods_sale_price = $goods_info['gu_final_price'] + $y_goods_price;
                    } else {
                        #提成
                        $goods_sale_price = $goods_info['ti_final_price'];
                    }
                    $order_goods[$i]['goods_sale_price'] = $goods_sale_price;  #运营商给客户的价格（展示在运营商）


                    //给供应商显示的商品价格（不包含加价）
                    $supplier_price += $order_goods[$i]['goods_original_price'] * $goods_info['goods_num'];
                    db('order')->where(['order_id' => $order_id])->update(['supplier_amount' => $supplier_price]);

                    $order_goods[$i]['goods_type'] = 1;
                    $ifgroupbuy = false;
                    // if (isset($goods_info['ifgroupbuy'])) {
                    //     $ifgroupbuy = true;
                    //     $order_goods[$i]['goods_type'] = 2;
                    // } elseif (isset($goods_info['ifxianshi'])) {
                    //     $order_goods[$i]['goods_type'] = 3;
                    // } elseif (isset($goods_info['ifzengpin'])) {
                    //     $order_goods[$i]['goods_type'] = 5;
                    // } elseif (isset($goods_info['ifpintuan']) && intval($this->_post_data['pintuan_id']) > 0) {
                    //     //     //拼团订单
                    //     /**
                    //      * $goods_info['ifpintuan'] , $goods_info['pintuan_id']  此数据是通过商品ID 获取到是否为拼团订单
                    //      * $this->_post_data['pintuan_id']   $this->_post_data['pintuangroup_id'] 此数据是通过post 过来的数据，用来判断是否为首个拼团订单:0首个订单 其他为所属订单
                    //      */
                    //     $order_goods[$i]['goods_type'] = 6;
                    //     // //拼团订单的特殊性,还需要额外的进行处理.
                    //     $pintuangroup_id = intval($this->_post_data['pintuangroup_id']);
                    //     $pintuan_id = intval($this->_post_data['pintuan_id']);

                    //     $pintuanorder_isfirst = 0; #是否为首团订单
                    //     if ($pintuangroup_id == 0) {
                    //         //首团订单新增
                    //         $data = array(
                    //             'pintuan_id' => $pintuan_id,
                    //             'pintuangroup_goods_id' => $goods_info['goods_id'],
                    //             'pintuangroup_joined' => 0,
                    //             'pintuangroup_limit_number' => $goods_info['pintuan_info']['pintuan_limit_number'],
                    //             'pintuangroup_limit_hour' => $goods_info['pintuan_info']['pintuan_limit_hour'],
                    //             'pintuangroup_headid' => $member_id,
                    //             'pintuangroup_starttime' => TIMESTAMP,
                    //         );
                    //         $pintuangroup_id = model('ppintuangroup')->addPpintuangroup($data);
                    //         //拼团统计新增开团数量
                    //         db('ppintuan')->where('pintuan_id', $pintuan_id)->setInc('pintuan_count');
                    //         $pintuanorder_isfirst = 1;
                    //     }
                    //     // //新增订单
                    //     $data = array(
                    //         'pintuan_id' => $pintuan_id,
                    //         'pintuangroup_id' => $pintuangroup_id,
                    //         'order_id' => $order_id,
                    //         'order_sn' => $order['order_sn'],
                    //         'pintuanorder_isfirst' => $pintuanorder_isfirst,
                    //     );
                    //     model('ppintuanorder')->addPpintuanorder($data);
                    //     //开团统计新增人数
                    //     db('ppintuangroup')->where('pintuangroup_id', $pintuangroup_id)->setInc('pintuangroup_joined');
                    //     //下单后清除缓存
                    //     model('ppintuan')->_dGoodsPintuanCache($goods_info['pintuan_info']['pintuan_goods_commonid']);
                    // } elseif (isset($goods_info['ifbargain']) && $goods_info['ifbargain']) {
                    //     // //砍价订单
                    //     $order_goods[$i]['goods_type'] = 8;
                    //     if (!model('pbargainorder')->editPbargainorder(array('bargainorder_id' => $goods_info['promotions_id']), array('order_id' => $order_id))) {
                    //         exception('砍价活动更新失败');
                    //     }
                    // } elseif (isset($goods_info['ifmgdiscount'])) {
                    //     $order_goods[$i]['goods_type'] = 7;
                    // } else {
                    //     $order_goods[$i]['goods_type'] = 1;
                    // }
                    $order_goods[$i]['promotions_id'] = isset($goods_info['promotions_id']) ? $goods_info['promotions_id'] : 0;

                    $order_goods[$i]['commis_rate'] = floatval(@$store_gc_id_commis_rate_list[$store_id][$goods_info['gc_id']]);

                    $order_goods[$i]['gc_id'] = $goods_info['gc_id'];
                    //计算商品金额
                    $goods_total = $goods_info['goods_price'] * $goods_info['goods_num'];
                    //计算本件商品优惠金额   zzzc
                    $promotion_value = floor($goods_total * ($promotion_rate));
                    // $order_goods[$i]['goods_pay_price'] = $goods_total - $promotion_value;

                    $order_goods[$i]['goods_pay_price'] = $order_goods[$i]['goods_price'] / $order_goods[$i]['goods_num'];
                    #如果存在满赠 价格为0
                    if (isset($goods_info['is_full'])) {
                        $order_goods[$i]['goods_pay_price'] = 0;
                    }
                    $promotion_sum += $promotion_value;
                    $i++;

                    //存储库存报警数据
                    if (isset($goods_info['goods_storage_alarm']) && $goods_info['goods_storage_alarm'] >= ($goods_info['goods_storage'] - $goods_info['goods_num'])) {
                        $param = array();
                        $param['common_id'] = $goods_info['goods_commonid'];
                        $param['sku_id'] = $goods_info['goods_id'];
                        $notice_list['goods_storage_alarm'][$goods_info['store_id']] = $param;
                    }
                }
                // elseif (!empty($goods_info['bl_goods_list']) && is_array($goods_info['bl_goods_list'])) {
                //     $ifgroupbuy = false;
                //     //优惠套装
                //     foreach ($goods_info['bl_goods_list'] as $bl_goods_info) {
                //         $order_goods[$i]['order_id'] = $order_id;
                //         $order_goods[$i]['goods_id'] = $bl_goods_info['goods_id'];
                //         $order_goods[$i]['store_id'] = $store_id;
                //         $order_goods[$i]['goods_name'] = $bl_goods_info['goods_name'];
                //         $order_goods[$i]['goods_price'] = $bl_goods_info['blgoods_price'];
                //         $order_goods[$i]['goods_num'] = $goods_info['goods_num'];
                //         $order_goods[$i]['goods_image'] = $bl_goods_info['goods_image'];
                //         $order_goods[$i]['buyer_id'] = $member_id;
                //         $order_goods[$i]['goods_type'] = 4;
                //         $order_goods[$i]['promotions_id'] = $bl_goods_info['bl_id'];
                //         $order_goods[$i]['commis_rate'] = floatval(@$store_gc_id_commis_rate_list[$store_id][$goods_info['gc_id']]);
                //         $order_goods[$i]['gc_id'] = $bl_goods_info['gc_id'];

                //         //计算商品实际支付金额(goods_price减去分摊优惠金额后的值)
                //         $goods_total = $bl_goods_info['blgoods_price'] * $goods_info['goods_num'];
                //         //计算本件商品优惠金额
                //         $promotion_value = floor($goods_total * ($promotion_rate));
                //         // $order_goods[$i]['goods_pay_price'] = $goods_total - $promotion_value;
                //         $order_goods[$i]['goods_pay_price'] = $order_goods[$i]['goods_price'] / $order_goods[$i]['goods_num'];
                //         $promotion_sum += $promotion_value;
                //         $i++;

                //         //存储库存报警数据
                //         if ($bl_goods_info['goods_storage_alarm'] >= ($bl_goods_info['goods_storage'] - $goods_info['goods_num'])) {
                //             $param = array();
                //             $param['common_id'] = $bl_goods_info['goods_commonid'];
                //             $param['sku_id'] = $bl_goods_info['goods_id'];
                //             $notice_list['goods_storage_alarm'][$bl_goods_info['store_id']] = $param;
                //         }
                //     }
                // }
            }
            //将因舍出小数部分出现的差值补到最后一个商品的实际成交价中(商品goods_price=0时不给补，可能是赠品)
            if ($promotion_total > $promotion_sum) {
                $i--;
                for ($i; $i >= 0; $i--) {
                    if (floatval($order_goods[$i]['goods_price']) > 0) {
                        // $order_goods[$i]['goods_pay_price'] -= $promotion_total - $promotion_sum;
                        $order_goods[$i]['goods_pay_price'] = $order_goods[$i]['goods_price'] / $order_goods[$i]['goods_num'];
                        break;
                    }
                }
            }


            $insert = $order_model->addOrdergoods($order_goods);


            if (!$insert) {
                exception('订单保存失败[未生成商品数据]');
            }

            $order_list[$order_id]['order_goods'] = $order_goods;
            // p($order_list);die;
            //存储商家发货提醒数据
            if ($store_pay_type_list[$store_id] == 'offline') {
                $notice_list['new_order'][$order['store_id']] = array('order_sn' => $order['order_sn']);
            }
        }


        #存数据
        // $total = $this->_order_data['total'];

        $order_ids_array = array_keys($order_list);
        $order_ids = implode(',', $order_ids_array);
        $total['order_ids'] = $order_ids;

        $order_goods_info = db('ordergoods')->where('order_id', 'in', $order_ids)->select();
        if (!empty($order_goods_info)) {
            $total['goods_ids'] = implode(',', array_column($order_goods_info, 'goods_id'));
            $total['ordergoods_ids'] = implode(',', array_column($order_goods_info, 'rec_id'));
        }

        /*   #shen
           $order_goods_info = db('ordergoods')->where('order_id', $order_id)->select();
         //  p($input_address_info);die;
           if (!empty($order_goods_info)) {
               $app_order['goods_ids'] = implode(',', array_column($order_goods_info, 'goods_id'));
              // $app_order['ordergoods_ids'] = implode(',', array_column($order_goods_info, 'rec_id'));
           }*/

        //大订单返回相应的数据
        //保存数据

        #商品的总价
        $goods_prices = 0;
        foreach ($store_final_goods_total as $k => $v) {
            // $goods_prices = $v++;
            $goods_prices += $v;
        }
        #运费总价
        $freight_prices = 0;
        foreach ($store_freight_total as $k => $v) {
            $freight_prices += $v;
            // $freight_prices = $v++;
        }
        #订单总价
        $prices = 0;
        foreach ($store_final_order_total as $k => $v) {
            $prices += $v;
        }
        $total['goods_prices'] = $goods_prices;

        $total['freight'] = $freight_prices;
        $total['price'] = $prices;

        //$app_order['order_ids'] = $order_id;
        $total['order_status'] = 0;
        // $app_order['order_status'] = 0;
        /*  $app_order['order_sn'] = time().'123';
          $app_order['create_time'] = time();
          $app_order['user_id'] = $member_id;
          $app_order['user_name'] = $reciver_name;
          $app_order['phone'] = $input_address_info['address_tel_phone'];
          $app_order['user_address'] = $input_address_info['area_info'] . ' ' . $input_address_info['address_detail'];
  */
        $total['order_sn'] = time() . '123';
        $total['pay_sn'] = $pay_sn;
        $total['app_order_type'] = 1;
        $total['create_time'] = time();
        $total['member_name'] = $member_name;
        $total['user_id'] = $member_id;
        $total['user_name'] = $reciver_name;
        $total['phone'] = $input_address_info['address_tel_phone'];
        $total['user_address'] = $input_address_info['area_info'] . ' ' . $input_address_info['address_detail'];
        //下单使用了多少积分
        $total['use_integral'] = $fina_integral;
        if ($is_integral == 1) {
            $total['use_integral_text'] = $price_ratio['value'] . '元=' . $integral_ratio['value'] . '积分';
        }
        //返回了多少积分
        $total['return_jifen'] = $count;
        $total['voucher_id'] = $voucher_id;
        //下单使用优惠劵优惠了多少钱
        $total['voucher_price'] = $voucher_price;
        //满减满赠
        if ($total_deduction) {
            $total['total_deduction'] = implode(',', $total_deduction);
            $total['total_deduction_text'] = implode(',', $deduction_text);
            $total['deduction_id'] = implode(',', $deduction_ids);
        }

        db('app_order')->data($total)->insert();
        $Id = db('app_order')->getLastInsID();

        foreach ($order_ids_array as $k => $v) {
            db('order')->data(['apporder_id' => $Id])->where(['order_id' => $v])->update();
        }

        #更新大订单表的总折扣、总安装费
        $app_order_info = db('app_order')->where(['app_order_id' => $Id])->find();
        $app_order_ids = explode(',', $app_order_info['ordergoods_ids']);
        $app_count_discount = 0;
        $app_count_door = 0;
        foreach ($app_order_ids as $k => $v) {
            $son_order_info = db('ordergoods')->where(['rec_id' => $v])->find();
            $app_count_discount += $son_order_info['discount_price'];
            $app_count_door += $son_order_info['door_count_price'];
        }

        //重新计算商品价格
        if ($post['ifcart'] == 0) {
            //直接购买 总金额减去折扣金额,满减，优惠劵金额  
            // $price = $prices - $app_count_discount - $amount_reduction - $voucher_price; #实际支付金额
            // $goods_prices = $goods_prices - $app_count_discount - $amount_reduction; #总商品金额
            $price = $prices - $amount_reduction - $voucher_price;
            $goods_prices = $goods_prices - $amount_reduction; #总商品金额
        } else {
            //购物车
            $price = $prices - $amount_reduction - $voucher_price; #实际支付金额
            $goods_prices = $goods_prices; #总商品金额
        }

        db('app_order')->where(['app_order_id' => $Id])->data(['app_count_discount' => $app_count_discount, 'app_count_door' => $app_count_door, 'price' => $price, 'goods_prices' => $goods_prices])->update();

        //判断总额  来送优惠劵
        // 1、先查询优惠劵赠送表
        $voucher_type_list = db('voucher_type')->where(['type_status' => 1, 'is_del' => 0])->select();
        foreach ($voucher_type_list as $key => $value) {
            //判断如果是满赠优惠劵的话  并且商品总价大于满的金额 赠送优惠劵
            if ($value['pattern_id'] == 3 && $place_price > $value['full_price']) {
                $voucher_place_info = db('voucher')->where(['voucher_id' => $value['voucher_id']])->find();
                //判断优惠劵的数量还有没有了
                if ($voucher_place_info['surplus_count'] != 0) {
                    $voucher_data = [
                        'member_id' => $member_id,
                        'voucher_type_id' => 3,
                        'voucher_id' => $value['voucher_id'],
                        'voucher_name' => $voucher_place_info['voucher_title'],
                        'is_used' => 1,
                        'create_time' => time(),
                        'due_time' => time() + ($voucher_place_info['use_date'] * 24 * 60 * 60),
                        'voucher_collection_price' => $voucher_place_info['voucher_price']
                    ];
                    db('voucher_collection')->insert($voucher_data);
                    //统计送出去了多少个优惠劵
                    $surplus_count = $voucher_place_info['surplus_count'] - 1;
                    db('voucher')->where(['voucher_id' => $value['voucher_id']])->update(['surplus_count' => $surplus_count]);
                }
            }
        }

        #会员下单生成统计数据  （生成客户统计的会员分析数据）
        $statm_data = [
            'statm_memberid' => $member_id,
            'statm_membername' => $member_name,
            'statm_time' => time(),
            'statm_ordernum' => 1,
            'statm_orderamount' => $integral_price,
            'statm_goodsnum' => $merchandise
        ];
        $stat_model->generateMember($statm_data);


        #会员下单生成商城数据统计  (获取当前的年月)（生成商城订单分析--的四个统计金额）
        $statis_data = [
            'os_order_totals' => $integral_price, #订单金额
            'os_result_totals' => $markup_price, #平台设置加价的值
            'os_createdate' => time()
        ];
        $stat_model->generateMall($statis_data);

        //保存数据
        $this->_order_data['app_order_sn'] = $total['order_sn'];
        $this->_order_data['pay_sn'] = $pay_sn;
        $this->_order_data['total'] = $pay_sn;
        $this->_order_data['order_list'] = $order_list;
        $this->_order_data['notice_list'] = $notice_list;
        $this->_order_data['ifgroupbuy'] = $ifgroupbuy;
    }

    /**
     * 充值卡、预存款支付
     */
    private function _createOrderStep5()
    {
        if (empty($this->_post_data['password']))
            return;
        $buyer_info = model('member')->getMemberInfoByID($this->_member_info['member_id']);
        if ($buyer_info['member_paypwd'] == '' || $buyer_info['member_paypwd'] != md5($this->_post_data['password']))
            exception('支付密码错误');

        //使用充值卡支付
        if (!empty($this->_post_data['rcb_pay'])) {
            $order_list = $this->_logic_buy_1->rcbPay($this->_order_data['order_list'], $this->_post_data, $buyer_info);
        }

        //使用预存款支付
        if (!empty($this->_post_data['pd_pay'])) {
            $this->_logic_buy_1->pdPay(isset($order_list) ? $order_list : $this->_order_data['order_list'], $this->_post_data, $buyer_info);
        }
    }

    /**
     * 订单后续其它处理
     */
    private function _createOrderStep6()
    {

        $ifcart = $this->_post_data['ifcart'];
        $goods_buy_quantity = $this->_order_data['goods_buy_quantity'];
        $input_voucher_list = $this->_order_data['input_voucher_list'];
        $store_cart_list = $this->_order_data['store_cart_list'];
        $input_buy_items = $this->_order_data['input_buy_items'];
        $order_list = $this->_order_data['order_list'];
        $input_address_info = $this->_order_data['input_address_info'];
        $notice_list = $this->_order_data['notice_list'];
        $goodsfcode_id = $this->_order_data['goodsfcode_id'];
        $ifgroupbuy = $this->_order_data['ifgroupbuy'];

        //变更库存和销量
        \mall\queue\QueueClient::push('createOrderUpdateStorage', $goods_buy_quantity);

        // p($aa);die;

        //更新使用的代金券状态
        if (!empty($input_voucher_list) && is_array($input_voucher_list)) {
            \mall\queue\QueueClient::push('editVoucherState', $input_voucher_list);
        }

        //更新F码使用状态
        if ($goodsfcode_id) {
            \mall\queue\QueueClient::push('updateGoodsfcode', $goodsfcode_id);
        }

        //更新抢购购买人数和数量
        if ($ifgroupbuy) {
            foreach ($store_cart_list as $goods_list) {
                foreach ($goods_list as $goods_info) {
                    if ($goods_info['ifgroupbuy'] && $goods_info['groupbuy_id']) {
                        $groupbuy_info = array();
                        $groupbuy_info['groupbuy_id'] = $goods_info['groupbuy_id'];
                        $groupbuy_info['quantity'] = $goods_info['goods_num'];
                        \mall\queue\QueueClient::push('editGroupbuySaleCount', $groupbuy_info);
                    }
                }
            }
        }


        #处理分账
        #获取运营商身份
        $yys_id = get_parent_store_id();
        $member_info = db('store')->where('store_id', $yys_id)->find();
        $type = $member_info['supplier_type'];

        //处理总利润
        $update_order_data = [];
        $g_profit_content = [];
        $y_profit_content = [];
        $p_profit_content = [];

        foreach ($order_list as $k => $v) {
            $order_info = db('order')->where('order_id', $k)->find();
            foreach ($v['order_goods'] as $kk => $vv) {
                $goods_info = db('goods')->where('goods_id', $vv['goods_id'])->find();
                $waybill_info = db('waybill')->where('waybill_id', $goods_info['waybill_id'])->find();

                #供应商总利润
                $g_profit_content[$kk]['goods_id'] = $goods_info['goods_id'];
                $g_profit_content[$kk]['goods_price'] = $goods_info['goods_price'];
                $g_profit_content[$kk]['g_goods_price'] = $goods_info['goods_price'] * $vv['goods_num'];
                $g_profit_content[$kk]['is_home'] = $vv['is_home'];
                $g_profit_content[$kk]['waybill_type'] = $goods_info['waybill_type'];
                $g_profit_content[$kk]['home_price'] = $waybill_info['home_price'];


                #平台总利润
                $p_profit_content[$kk]['goods_id'] = $goods_info['goods_id'];
                $p_profit_content[$kk]['yys_type'] = $type;
                $p_profit_content[$kk]['goods_price'] = $goods_info['goods_price'];
                $p_profit_content[$kk]['is_install'] = $vv['is_goods_door'];
                $p_profit_content[$kk]['install_money'] = $goods_info['install_money'];
                if ($type == 1) {
                    #加价运营商
                    $p_profit_content[$kk]['gu_final_price'] = $goods_info['gu_final_price'];

                    $p_jia = ($goods_info['gu_final_price'] - $goods_info['goods_price']) * $vv['goods_num'];
                    $p_profit_content[$kk]['p_goods_price'] = $p_jia;
                } else {
                    #提成运营商
                    $p_profit_content[$kk]['ti_final_price'] = $goods_info['ti_final_price'];
                    $p_profit_content[$kk]['deduct_market'] = $member_info['deduct_market'];

                    $p_jia = ($goods_info['ti_final_price'] - $goods_info['goods_price']) * $vv['goods_num'];
                    $p_jias = $p_jia - $p_jia * $member_info['deduct_market'] / 100;
                    $p_profit_content[$kk]['p_goods_price'] = $p_jias;
                }


                #运营商总利润
                $y_profit_content[$kk]['goods_id'] = $goods_info['goods_id'];
                $y_profit_content[$kk]['yys_type'] = $type;
                $y_profit_content[$kk]['goods_price'] = $goods_info['goods_price'];
                if ($type == 1) {
                    #加价运营商
                    $y_profit_content[$kk]['gu_final_price'] = $goods_info['gu_final_price'];
                    $y_goods_info = db('y_goods')->where('goods_id', $goods_info['goods_id'])->where('store_id', $yys_id)->find();
                    $y_goods_price = empty($y_goods_info['price']) ? 0 : $y_goods_info['price'];
                    $y_profit_content[$kk]['y_goods_price'] = $y_goods_price * $vv['goods_num'];
                } else {
                    $y_profit_content[$kk]['ti_final_price'] = $goods_info['ti_final_price'];
                    $y_profit_content[$kk]['deduct_market'] = $member_info['deduct_market'];
                    #提成运营商
                    $y_profit_content[$kk]['y_goods_price'] = ($goods_info['ti_final_price'] - $goods_info['goods_price']) * $vv['goods_num'] * $member_info['deduct_market'] / 100;
                }


                #分担
                $app_order_info = db('app_order')->where('app_order_id', $order_info['apporder_id'])->find();

                $g_share_content[$kk]['goods_id'] = $goods_info['goods_id'];
                $g_share_content[$kk]['goods_price'] = $goods_info['goods_price'];

                $y_share_content[$kk]['goods_id'] = $goods_info['goods_id'];
                $y_share_content[$kk]['goods_price'] = $goods_info['goods_price'];

                $p_share_content[$kk]['goods_id'] = $goods_info['goods_id'];
                $p_share_content[$kk]['goods_price'] = $goods_info['goods_price'];

                #折扣
                if ($vv['is_discount']) {
                    $p_share_content[$kk]['is_discount'] = 1;
                    $g_share_content[$kk]['is_discount'] = 1;
                    $y_share_content[$kk]['is_discount'] = 1;

                    $discount_info = db('pxianshi')->where('xianshi_id', $vv['discount_id'])->find();
                    if ($discount_info) {
                        $p_share_content[$kk]['discount_content'] = json_encode($discount_info);
                        $g_share_content[$kk]['discount_content'] = json_encode($discount_info);
                        $y_share_content[$kk]['discount_content'] = json_encode($discount_info);

                        $g_discount_array[$kk] = $discount_info['supplier_share'] * $vv['discount_price'] / 100;
                        $y_discount_array[$kk] = $discount_info['proportion_share'] * $vv['discount_price'] / 100;
                        $p_discount_array[$kk] = $discount_info['platform_share'] * $vv['discount_price'] / 100;
                    } else {
                        $g_discount_array[$kk] = 0;
                        $y_discount_array[$kk] = 0;
                        $p_discount_array[$kk] = 0;
                    }
                } else {
                    $g_discount_array[$kk] = 0;
                    $y_discount_array[$kk] = 0;
                    $p_discount_array[$kk] = 0;
                }

                #满减满赠
                if ($v['avg_total_deduction']) {
                    $p_share_content['is_deduction'] = 1;
                    $g_share_content['is_deduction'] = 1;
                    $y_share_content['is_deduction'] = 1;

                    if (strstr($v['avg_total_deduction'], ';')) {
                        $deduction_array = explode(';', $v['avg_total_deduction']);
                        foreach ($deduction_array as $a => $b) {
                            $deduction_arrays = explode(',', $b);
                            $deduction_info = db('pmansong')->where('mansong_id', $deduction_arrays['0'])->find();
                            $p_share_content['deduction_content'][$a] = json_encode($deduction_info);
                            $g_share_content['deduction_content'][$a] = json_encode($deduction_info);
                            $y_share_content['deduction_content'][$a] = json_encode($deduction_info);

                            $g_deduction_array[$a] = $deduction_info['supplier_share'] * $deduction_arrays['1'] / 100;
                            $y_deduction_array[$a] = $deduction_info['proportion_share'] * $deduction_arrays['1'] / 100;
                            $p_deduction_array[$a] = $deduction_info['platform_share'] * $deduction_arrays['1'] / 100;
                        }
                    } else {


                        $deduction_arrays = explode(',', $v['avg_total_deduction']);
                        $deduction_info = db('pmansong')->where('mansong_id', $deduction_arrays['0'])->find();
                        $p_share_content['deduction_content'] = json_encode($deduction_info);
                        $g_share_content['deduction_content'] = json_encode($deduction_info);
                        $y_share_content['deduction_content'] = json_encode($deduction_info);

                        $g_deduction_array[0] = $deduction_info['supplier_share'] * $deduction_arrays['1'] / 100;
                        $y_deduction_array[0] = $deduction_info['proportion_share'] * $deduction_arrays['1'] / 100;
                        $p_deduction_array[0] = $deduction_info['platform_share'] * $deduction_arrays['1'] / 100;
                    }
                } else {
                    $p_share_content['is_deduction'] = 0;
                    $g_share_content['is_deduction'] = 0;
                    $y_share_content['is_deduction'] = 0;
                    $g_deduction_array[$kk] = 0;
                    $y_deduction_array[$kk] = 0;
                    $p_deduction_array[$kk] = 0;
                }
            }


            #供应商总利润
            $sum_goods_price = array_sum(array_column($g_profit_content, 'g_goods_price'));
            $update_order_data['g_profit'] = $sum_goods_price + $v['shipping_fee'];
            $update_order_data['g_profit_content'] = json_encode($g_profit_content);

            #平台总利润
            $update_order_data['p_profit'] = array_sum(array_column($p_profit_content, 'p_goods_price')) + $order_info['order_count_door'];
            $update_order_data['p_profit_content'] = json_encode($p_profit_content);

            #运营商总利润
            $update_order_data['y_profit'] = array_sum(array_column($y_profit_content, 'y_goods_price'));
            $update_order_data['y_profit_content'] = json_encode($y_profit_content);


            #优惠券
            if ($v['order_voucher']) {
                $p_share_content['is_voucher'] = 1;
                $g_share_content['is_voucher'] = 1;
                $y_share_content['is_voucher'] = 1;

                $voucher_info = db('voucher')->where('voucher_id', $app_order_info['voucher_id'])->find();
                if ($voucher_info) {
                    $p_share_content['voucher_content'] = json_encode($voucher_info);
                    $g_share_content['voucher_content'] = json_encode($voucher_info);
                    $y_share_content['voucher_content'] = json_encode($voucher_info);

                    $g_voucher = $v['order_voucher'] * $voucher_info['g_ratio'] / 100;
                    $y_voucher = $v['order_voucher'] * $voucher_info['y_ratio'] / 100;
                    $p_voucher = $v['order_voucher'] * $voucher_info['z_ratio'] / 100;
                } else {
                    $g_voucher = 0;
                    $y_voucher = 0;
                    $p_voucher = 0;
                }
            } else {
                $p_share_content['is_voucher'] = 0;
                $g_share_content['is_voucher'] = 0;
                $y_share_content['is_voucher'] = 0;

                $g_voucher = 0;
                $y_voucher = 0;
                $p_voucher = 0;
            }

            #积分
            if ($v['order_integral']) {
                $p_share_content['is_score'] = 1;
                $p_share_content['score_content'] = $app_order_info['use_integral_text'];
                $p_score = $v['order_integral'];
            } else {
                $p_score = 0;
            }

            #折扣
            if ($g_discount_array) {
                $g_discount = array_sum($g_discount_array);
                $y_discount = array_sum($y_discount_array);
                $p_discount = array_sum($p_discount_array);
            }

            #满减满赠
            if ($g_deduction_array) {
                $g_deduction = array_sum($g_deduction_array);
                $y_deduction = array_sum($y_deduction_array);
                $p_deduction = array_sum($p_deduction_array);
            }


            #总分担
            $update_order_data['g_share_money'] = round(($g_voucher + $g_discount + $g_deduction), 2);
            $update_order_data['y_share_money'] = round(($y_voucher + $y_discount + $y_deduction), 2);
            $update_order_data['p_share_money'] = round(($p_voucher + $p_discount + $p_deduction + $p_score), 2);

            $update_order_data['p_share_content'] = json_encode($p_share_content);
            $update_order_data['y_share_content'] = json_encode($y_share_content);
            $update_order_data['g_share_content'] = json_encode($g_share_content);

            #最总可分
            $update_order_data['p_price'] = $update_order_data['p_profit'] - $update_order_data['p_share_money'];
            $update_order_data['y_price'] = $update_order_data['y_profit'] - $update_order_data['y_share_money'];
            $update_order_data['g_price'] = $update_order_data['g_profit'] - $update_order_data['g_share_money'];

            db('order')->where('order_id', $k)->data($update_order_data)->update();
        }


        //删除购物车中的商品
        $this->delCart($ifcart, $this->_member_info['member_id'], array_keys($input_buy_items));
        cookie('cart_goods_num', '', -3600);

        //保存订单自提点信息
        if (config('delivery_isuse') && intval($input_address_info['dlyp_id'])) {
            $data = array();
            $data['mob_phone'] = $input_address_info['address_mob_phone'];
            $data['tel_phone'] = $input_address_info['address_tel_phone'];
            $data['reciver_name'] = $input_address_info['address_realname'];
            $data['dlyp_id'] = $input_address_info['dlyp_id'];
            foreach ($order_list as $v) {
                $data['order_sn_list'][$v['order_id']]['order_sn'] = $v['order_sn'];
                $data['order_sn_list'][$v['order_id']]['add_time'] = $v['add_time'];
            }
            \mall\queue\QueueClient::push('saveDeliveryOrder', $data);
        }
        //生成推广记录
        $this->addOrderInviter($order_list);
        //发送提醒类信息
        if (!empty($notice_list)) {
            foreach ($notice_list as $code => $value) {
                \mall\queue\QueueClient::push('sendStoremsg', array(
                    'code' => $code, 'store_id' => key($value), 'param' => current($value)
                ));
            }
        }
    }

    /**
     * 订单后续其它处理
     */
    private function _createOrderStep6_project($prodect_id)
    {

        //变更销量跟库存
        $post = $this->_post_data;
        $member_id = $this->_member_info['member_id'];

        //如果有优惠劵使用，变更优惠劵状态
        if (!empty($post['voucher_id'])) {
            //下完单改变状态
            db('voucher_collection')->where(['member_id' => $member_id, 'id' => $post['voucher_id']])->update(['is_used' => 2, 'used_time' => time()]);
        }

        //下单增加项目定制的销量
        $info = db('goodsproject')->where(['project_id' => $prodect_id])->find();
        $sale_nums = $info['sale_num'] + 1;
        db('goodsproject')->where(['project_id' => $prodect_id])->update(['sale_num' => $sale_nums]);
    }

    /**
     * 加密
     * @param array /string $string
     * @param int $member_id
     * @return mixed arrray/string
     */
    public function buyEncrypt($string, $member_id)
    {
        $buy_key = sha1(md5($member_id . '&' . MD5_KEY));
        if (is_array($string)) {
            $string = serialize($string);
        } else {
            $string = strval($string);
        }
        return ds_encrypt(base64_encode($string), $buy_key);
    }

    /**
     * 解密
     * @param string $string
     * @param int $member_id
     * @param number $ttl
     */
    public function buyDecrypt($string, $member_id, $ttl = 0)
    {
        $buy_key = sha1(md5($member_id . '&' . MD5_KEY));
        if (empty($string))
            return;
        $string = base64_decode(ds_decrypt(strval($string), $buy_key, $ttl));
        return ($tmp = @unserialize($string)) !== false ? $tmp : $string;
    }

    /**
     * 得到所购买的id和数量
     *
     */
    private function _parseItems($cart_id)
    {
        //存放所购商品ID和数量组成的键值对
        $buy_items = array();
        if (is_array($cart_id)) {
            foreach ($cart_id as $value) {
                if (preg_match_all('/^(\d{1,10})\|(\d{1,6})$/', $value, $match)) {
                    if (intval($match[2][0]) > 0) {
                        $buy_items[$match[1][0]] = $match[2][0];
                    }
                }
            }
        }
        return $buy_items;
    }

    /**
     * 从购物车数组中得到商品列表
     * @param unknown $cart_list
     */
    private function _getGoodsList($cart_list)
    {
        if (empty($cart_list) || !is_array($cart_list))
            return $cart_list;
        $goods_list = array();
        $i = 0;

        foreach ($cart_list as $key => $cart) {
            // var_dump(!$cart['storage_state']);exit;
            if (!$cart['state'] || !$cart['storage_state'])
                continue;
            //购买数量
            $quantity = $cart['goods_num'];
            if (!intval($cart['bl_id'])) {
                //获取商品详情
                $goods_info = db('goods')->where(['goods_id' => $cart['goods_id']])->find();
                //如果是普通商品
                $goods_list[$i]['goods_num'] = $quantity;
                $goods_list[$i]['goods_id'] = $cart['goods_id'];
                $goods_list[$i]['store_id'] = $cart['store_id'];
                $goods_list[$i]['gc_id'] = $cart['gc_id'];
                $goods_list[$i]['goods_name'] = $cart['goods_name'];
                $goods_list[$i]['goods_price'] = $cart['goods_price'];
                $goods_list[$i]['store_name'] = $cart['store_name'];
                $goods_list[$i]['goods_image'] = $cart['goods_image'];
                $goods_list[$i]['transport_id'] = $cart['transport_id'];
                $goods_list[$i]['goods_freight'] = $cart['goods_freight'];
                $goods_list[$i]['goods_vat'] = $cart['goods_vat'];
                $goods_list[$i]['is_goodsfcode'] = $cart['is_goodsfcode'];
                $goods_list[$i]['spec_values'] = $cart['spec_values'];
                $goods_list[$i]['is_install'] = $cart['is_install'];
                $goods_list[$i]['bl_id'] = 0;
                $goods_list[$i]['area'] = $goods_info['area'];
                $config = db('config')->where('code', 'qiniu_http')->find();
                $goods_list[$i]['goods_image_url'] = $config['value'] . '/' . $cart['goods_image'];
                $i++;
            } else {
                //如果是优惠套装商品
                foreach ($cart['bl_goods_list'] as $bl_goods) {
                    $goods_list[$i]['goods_num'] = $quantity;
                    $goods_list[$i]['goods_id'] = $bl_goods['goods_id'];
                    $goods_list[$i]['store_id'] = $cart['store_id'];
                    $goods_list[$i]['gc_id'] = $bl_goods['gc_id'];
                    $goods_list[$i]['goods_name'] = $bl_goods['goods_name'];
                    $goods_list[$i]['goods_price'] = $bl_goods['blgoods_price'];
                    $goods_list[$i]['store_name'] = $bl_goods['store_name'];
                    $goods_list[$i]['goods_image'] = $bl_goods['goods_image'];
                    $goods_list[$i]['transport_id'] = $bl_goods['transport_id'];
                    $goods_list[$i]['goods_freight'] = $bl_goods['goods_freight'];
                    $goods_list[$i]['goods_vat'] = $bl_goods['goods_vat'];
                    $goods_list[$i]['bl_id'] = $cart['bl_id'];
                    $i++;
                }
            }
        }
        return $goods_list;
    }

    /**
     * 从购物车数组中得到商品列表
     * @param unknown $cart_list
     */
    private function _getFullGoodsList($new_goods_info, $post)
    {
        if (empty($new_goods_info) || !is_array($new_goods_info))
            return $new_goods_info;
        $goods_list = array();
        $i = 0;
        foreach ($new_goods_info as $key => $cart) {
            $is_install = 0;
            if ($cart['install_money'] > 0) {
                $is_install = 1;
            }
            //购买数量
            $quantity = $cart['goods_num'];
            //如果是普通商品
            $goods_list[$i]['goods_num'] = $quantity;
            $goods_list[$i]['goods_id'] = $cart['goods_id'];
            $goods_list[$i]['store_id'] = $cart['store_id'];
            $goods_list[$i]['gc_id'] = $cart['gc_id'];
            $goods_list[$i]['goods_name'] = $cart['goods_name'];
            $goods_list[$i]['goods_price'] = 0;
            $goods_list[$i]['store_name'] = $cart['store_name'];
            $goods_list[$i]['goods_image'] = $cart['goods_image'];
            $goods_list[$i]['transport_id'] = $cart['transport_id'];
            $goods_list[$i]['goods_freight'] = $cart['goods_freight'];
            $goods_list[$i]['goods_vat'] = $cart['goods_vat'];
            $goods_list[$i]['is_goodsfcode'] = $cart['is_goodsfcode'];
            $goods_list[$i]['spec_values'] = $cart['spec_values'];
            $goods_list[$i]['area'] = $cart['area'];
            $goods_list[$i]['is_install'] = $is_install;
            $config = db('config')->where('code', 'qiniu_http')->find();
            $goods_list[$i]['goods_image_url'] = $config['value'] . '/' . $cart['goods_image'];
            $i++;
        }
        return $goods_list;
    }

    /**
     * 将下单商品列表转换为以店铺ID为下标的数组
     *
     * @param array $cart_list
     * @return array
     */
    private function _getStoreCartList($cart_list)
    {
        if (empty($cart_list) || !is_array($cart_list))
            return $cart_list;
        $new_array = array();
        foreach ($cart_list as $cart) {
            $goods_info = db('goods')->alias('g')
                ->join('brand b', 'b.brand_id = g.brand_id')
                ->where(['goods_id' => $cart['goods_id']])
                ->find();
            $cart['goods_name'] = $goods_info['brand_name'] . '  ' . $cart['goods_name'];
            $new_array[$cart['store_id']][] = $cart;
        }
        return $new_array;
    }

    /**
     * 将下单商品列表转换为以店铺ID为下标的数组
     *
     * @param array $cart_list
     * @return array
     */
    private function _getFullStoreCartList($new_goods_info)
    {
        if (empty($new_goods_info) || !is_array($new_goods_info))
            return $new_goods_info;
        $new_array = array();
        foreach ($new_goods_info as $cart) {
            $new_array[$cart['store_id']][] = $cart;
        }
        return $new_array;
    }

    /**
     * 本次下单是否需要码及F码合法性
     * 无需使用F码，返回 true
     * 需要使用F码，返回($goodsfcode_id/false)
     */
    private function _checkFcode($goods_list, $fcode)
    {
        $is_goodsfcode = false;
        foreach ($goods_list as $k => $v) {
            if ($v['is_goodsfcode'] == 1) {
                $is_goodsfcode = true;
                break;
            }
        }
        if (!$is_goodsfcode)
            return true;
        if (empty($fcode) || count($goods_list) > 1) {
            return false;
        }
        $goods_info = $goods_list[0];
        $fcode_info = $this->checkFcode($goods_info['goods_commonid'], $fcode);
        if ($fcode_info['code'] && !$fcode_info['data']['goodsfcode_state']) {
            return intval($fcode_info['data']['goodsfcode_id']);
        } else {
            return false;
        }
    }


    /**
     * 购买第二步
     * @param array $post
     * @param int $member_id
     * @param string $member_name
     * @param string $member_email
     * @return array
     */
    public function buyStep3($post, $member_id, $member_name, $member_email)
    {

        $this->_member_info['member_id'] = $member_id;
        $this->_member_info['member_name'] = $member_name;
        $this->_member_info['member_email'] = $member_email;
        $this->_post_data = $post;

        try {

            $order_model = model('order');
            $order_model->startTrans();


            //第1步 表单验证
            $aa = $this->_createOrderStep1();

            //p($aa);die;
            //第2步 得到购买商品信息
            $bb = $this->_createOrderStep2();
            //p($bb);die;
            // echo 111;die;
            //第3步 得到购买相关金额计算等信息
            $cc = $this->_createOrderStep3();

            // p($cc);die;
            //第4步 生成订单  ,$post['voucher_id']
            $dd = $this->_createOrderStep4($post['is_integral'], $post['amount_reduction'], $post['voucher_id']);
            // p($dd);die;

            //第5步 处理预存款
            $ee = $this->_createOrderStep5();

            // p($ee);die;
            $order_model->commit();

            //第6步 订单后续处理
            $gg = $this->_createOrderStep6();
            // p($gg);die;

            return ds_callback(true, '', $this->_order_data);
        } catch (\think\Exception $e) {
            $this->rollback();
            return ds_callback(false, $e->getMessage());
        }
    }


    /**
     *
     *
     * /**
     * 项目定制购买，商城订单第二步
     * @param array $post
     * @param int $member_id
     * @param string $member_name
     * @param string $member_email
     * @return array
     */
    public function buyStep4($post, $member_id, $member_name, $member_email)
    {

        $this->_member_info['member_id'] = $member_id;
        $this->_member_info['member_name'] = $member_name;
        $this->_member_info['member_email'] = $member_email;
        $this->_post_data = $post;

        try {

            $order_model = model('order');
            $order_model->startTrans();
            //第1步 表单验证
            $aa = $this->_createProjectOrderStep1();
            //p($aa);die;
            //第2步 得到购买商品信息
            $bb = $this->_createOrderStep2_project();


            //第3步 生成订单  ,$post['voucher_id']
            $dd = $this->_createOrderStep4_project($post, $post['prodect_id'], $post['is_integral']);
            // p($dd);die;

            $order_model->commit();

            //第6步 订单后续处理  (变更销量，修改优惠劵使用状态)
            $gg = $this->_createOrderStep6_project($post['prodect_id']);
            // p($gg);die;

            return ds_callback(true, '', $this->_order_data);
        } catch (\think\Exception $e) {
            $this->rollback();
            return ds_callback(false, $e->getMessage());
        }
    }


    //2/13


    /**
     * 得到购买商品信息
     *
     */
    private function _createOrderStep2_project()
    {

        $post = $this->_post_data;

        $input_buy_items = $this->_order_data['input_buy_items'];
        if ($post['ifcart']) {
            //购物车列表
            $cart_model = model('cart');
            $condition = array(
                'cart_id' => array('in', array_keys($input_buy_items)), 'buyer_id' => $this->_member_info['member_id']
            );
            $cart_list = $cart_model->getCartList('db', $condition);

            //购物车列表 [得到最新商品属性及促销信息]
            $cart_list = $this->_logic_buy_1->getGoodsCartList($cart_list);

            // p($cart_list);die;
            //商品列表 [优惠套装子商品与普通商品同级罗列]
            $goods_list = $this->_getGoodsList($cart_list);


            //以店铺下标归类
            $store_cart_list = $this->_getStoreCartList($cart_list);
        } else {

            //来源于直接购买
            $goods_id = key($input_buy_items);
            $quantity = current($input_buy_items);


            //额外数据用来处理拼团等其他活动
            $pintuan_id = isset($post['pintuan_id']) ? intval($post['pintuan_id']) : 0;
            $extra = array();
            if ($pintuan_id > 0) {
                $extra['pintuan_id'] = $pintuan_id; #拼团ID
                #是否为开团订单
                $extra['pintuangroup_id'] = empty(input('param.pintuangroup_id')) ? 0 : intval(input('param.pintuangroup_id'));
            }
            $bargainorder_id = isset($post['bargainorder_id']) ? intval($post['bargainorder_id']) : 0;
            if ($bargainorder_id > 0) {
                $extra['bargainorder_id'] = $bargainorder_id; #砍价ID
            }

            //商品信息[得到最新商品属性及促销信息]
            $goods_info = $this->_logic_buy_1->getGoodsOnlineInfo($goods_id, intval($quantity), $extra, $this->_member_info['member_id']);
            if (empty($goods_info)) {
                exception('商品已下架或不存在');
            }

            //进一步处理数组
            $store_cart_list = array();
            $goods_list = array();
            $goods_list[0] = $store_cart_list[$goods_info['store_id']][0] = $goods_info;
        }
        //F码验证
        $goodsfcode_id = '';
        if (!empty($post['fcode'])) {
            $goodsfcode_id = $this->_checkFcode($goods_list, $post['fcode']);
            if (!$goodsfcode_id) {
                exception('F码商品验证错误');
            }
        }


        $this->_order_data['goodsfcode_id'] = $goodsfcode_id;

        $this->_order_data['goods_list'] = $goods_list;
        $this->_order_data['store_cart_list'] = $store_cart_list;
    }


    /**
     * 生成项目定制订单
     * @param array $input
     * @return array array(支付单sn,订单列表) ,$voucher_id
     * @throws Exception
     */
    private function _createOrderStep4_project($post, $prodect_id, $is_integrals)
    {
        extract($this->_order_data);

        $member_id = $this->_member_info['member_id'];
        $member_name = $this->_member_info['member_name'];
        $member_email = $this->_member_info['member_email'];

        //获取项目定制总价（总合计金额）
        $where['project_id'] = $prodect_id;
        $project_info = db('goodsproject')->where($where)->find();
        // $place_price = $project_info['total_price'] + $project_info['fee_price'] + $project_info['charge_price'] + $project_info['plementation_price'];
        $place_price = $project_info['total_price'];

        //是否使用积分  0—未使用 1—使用
        $is_integral = $is_integrals;

        //如果用户使用优惠劵了  获取优惠劵的面额
        if (!empty($post['voucher_id'])) {
            //获取优惠劵信息
            $voucher_info = db('voucher_collection')->where(['id' => $post['voucher_id']])->find();
            $voucher_price = $voucher_info['voucher_collection_price'];
        } else {
            $voucher_price = 0;
        }

        $fina_integral = 0; #使用了多少积分
        $fina_price = 0; #积分抵扣了多少钱
        //如果用户使用了积分
        if ($is_integral == 1) {
            //获取比例  订单总金额/比例==商品总价转换为积分（积分）
            //现有积分 > 商品总价转换为积分（积分） -->(使用商品总价转换为积分（积分）)
            //现有积分 < 商品总价转换为积分（积分） -->(现有积分)
            //商品价格 - 上面的积分*比例
            $member_info = db('member')->where(['member_id' => $member_id])->find();
            //积分数量
            $integral_ratio = db('config')->where('code', 'integral_ratio')->find();
            //金额数量
            $price_ratio = db('config')->where('code', 'price_ratio')->find();
            //比例
            $bili = $price_ratio['value'] / $integral_ratio['value'];

            //获取商品总价可以转化多少积分  如果有优惠劵的话 减去优惠劵的面额   (商品总价需要用多少积分)
            $count_integral = ($place_price - $voucher_price) / $bili;

            //获取要使用多少积分
            if ($member_info['member_points'] > $count_integral) {
                $fina_integral = $count_integral;
            } else {
                $fina_integral = $member_info['member_points'];
            }

            // 项目定制的总价 - 积分抵扣的金额 - 优惠劵减的金额
            $integral_price = $place_price - ($fina_integral * $bili) - $voucher_price;

            $fina_price = $fina_integral * $bili;
            //下完单减积分
            $update_integral = $member_info['member_points'] - $fina_integral;
            db('member')->where(['member_id' => $member_id])->update(['member_points' => $update_integral]);

            #生成积分消费日志
            $points_info = [
                'pl_memberid' => $member_id,
                'pl_membername' => $member_name,
                'pl_points' => '-' . $fina_integral,
                'pl_addtime' => time(),
                'pl_desc' => '购买商品',
                'pl_stage' => 'order',
                'pl_balance' => $update_integral
            ];
            db('pointslog')->insertGetId($points_info);
        } else {
            // 不使用   项目定制的总价 - 优惠劵减的金额
            $integral_price = $place_price - $voucher_price;
        }

        //获取收货人信息
        list($reciver_info, $reciver_name) = $this->_logic_buy_1->getReciverAddr($input_address_info);

        // 1、生成支付单信息
        $order_model = new \app\common\model\Order();
        $pay_sn = makePaySn($member_id);
        $order_pay = array();
        $order_pay['pay_sn'] = $pay_sn;
        $order_pay['buyer_id'] = $member_id;
        $order_pay_id = $order_model->addOrderpay($order_pay);
        if (!$order_pay_id) {
            exception('订单保存失败[未生成支付单]');
        }

        // 2、首先生成项目定制订单列表信息
        $config = db('config')->where('code', 'qiniu_http')->find();
        $yys_id = get_parent_store_id();
        $yys_info = db('store')->where('store_id', $yys_id)->find();

        $order_project = array();
        $order_project['order_sn'] = $this->_logic_buy_1->makeOrderSn($order_pay_id);
        $order_project['pay_sn'] = $pay_sn;
        $order_project['project_id'] = $prodect_id;
        $order_project['buyer_id'] = $member_id;
        $order_project['buyer_name'] = $member_name;
        $order_project['buyer_email'] = $member_email;
        $order_project['add_time'] = TIMESTAMP;
        $order_project['payment_code'] = $post['pay_name'];
        #商品总价
        $order_project['goods_amount'] = $integral_price;

        #订单总价  (合计金额：所有费用相加；实际支付费用，减去积分和优惠券)
        $order_project['order_amount'] = $place_price;

        #实际支付金额
        $order_project['actual_amount'] = $place_price - ($voucher_price + $fina_price);

        #订单状态
        $order_project['order_state'] = 10;
        $order_project['order_from'] = $post['order_from'];
        #使用了多少积分
        $order_project['order_integral'] = $fina_integral;
        #项目定制信息
        $order_project['project_name'] = $project_info['project_title'];
        $order_project['project_image'] = $config['value'] . '/' . $project_info['project_images'];
        $order_project['project_price'] = $project_info['total_price'];
        $order_project['fee_price'] = $project_info['fee_price'];
        $order_project['charge_price'] = $project_info['charge_price'];
        $order_project['plementation_price'] = $project_info['plementation_price'];
        #是否使用优惠劵
        $order_project['is_coupon'] = empty($post['voucher_id']) ? 0 : 1;
        $order_project['coupon_id'] = input('coupon_id', '1');
        $order_project['coupon'] = $voucher_price;
        //积分抵扣了多少钱
        $order_project['project_integral'] = $fina_price;
        $order_project['yys_id'] = $yys_id;
        $order_project['yys_name'] = $yys_info['store_name'];
        $order_project['reciver_info'] = $reciver_info;
        $order_project['reciver_name'] = $reciver_name;
        $order_project['reciver_city_id'] = $input_city_id;
        $order_project['address_id'] = $post['address_id'];

        $order_project['phone'] = $input_address_info['address_tel_phone'];
        $order_project['user_address'] = $input_address_info['area_info'] . ' ' . $input_address_info['address_detail'];

        $order_project_id = $order_model->addOrde2($order_project);

        if (!$order_project_id) {
            exception('订单保存失败[未生成项目订单]');
        }

        #生成订单缓存表，用于统计订单
        $order_cache = db('orderproject')->where(['order_id' => $order_project_id])->find();
        $res_cache = [
            'order_id' => $order_project_id,
            'order_sn' => $order_cache['order_sn'],
            'order_type' => 2,
            'order_add_time' => time(),
            'payment_code' => 1,
            'order_amount' => $order_cache['order_amount'],
            'evaluation_state' => $order_cache['evaluation_state'],
            'order_state' => $order_cache['order_state'],
            'refund_state' => $order_cache['refund_state'],
            'refund_amount' => $order_cache['refund_amount'],
            'order_from' => $order_cache['order_from'],
            'order_isvalid' => 1,
            'store_id' => 6,
            'store_name' => '过分的一大',
            'buyer_id' => $member_id,
            'buyer_name' => $member_name,
        ];
        db('statorder')->insertGetId($res_cache);


        //5、查项目定制表的商品  入库项目定制详情
        $goods_ids = explode(",", $project_info['goods_commonid']);
        //获取当前项目定制里面拥有的商品和数量
        $nums = db('goodsprojectnums')->where(['project_id' => $project_info['project_id']])->select();

        //商品总价
        $goods_total = 0;

        //获取数量  用户获取商品总价
        foreach ($nums as $key => $value) {
            if (in_array($value['goods_commonid'], $goods_ids)) {

                // $goods_info = db('goodscommon')->where(['goods_commonid'=>$value['goods_commonid']])->find();
                $goods_info = db('goods')->where(['goods_id' => $value['goods_commonid']])->find();

                //入库项目定制详情表

                #存的是项目定制列表订单的id
                $order_project_goods['order_id'] = $order_project_id;
                $order_project_goods['project_name'] = $project_info['project_title'];
                $order_project_goods['goods_name'] = $goods_info['goods_name'];
                $order_project_goods['goods_id'] = $value['goods_id'];
                $order_project_goods['goods_image'] = $config['value'] . '/' . $goods_info['goods_image'];
                $order_project_goods['store_id'] = $goods_info['store_id'];
                $order_project_goods['buyer_id'] = $member_id;
                $order_project_goods['buyer_name'] = $member_name;
                $order_project_goods['goods_price'] = $goods_info['goods_price'];

                $order_project_goods['goods_num'] = $value['num'];
                $goods_spec = implode(",", unserialize($goods_info['goods_spec']));
                $order_project_goods['goods_spec'] = $goods_spec;


                $order_project_goods_id = db('orderproject_goods')->insertGetId($order_project_goods);
                if (!$order_project_goods_id) {
                    exception('订单保存失败[未生成项目定制详情订单]');
                }

                $goods_total += $goods_info['goods_price'] * $value['num'];
            }
        }

        //更新商品总价
        db('order')->where(['orderproject_id' => $order_project_id])->update(['goods_amount' => $goods_total]);

        db('orderproject')->where(['order_id' => $order_project_id])->update(['goods_amount' => $goods_total]);


        //判断总额  来送优惠劵
        // 1、先查询优惠劵赠送表
        $voucher_type_list = db('voucher_type')->where(['type_status' => 1, 'is_del' => 0])->select();
        foreach ($voucher_type_list as $key => $value) {
            //判断如果是满赠优惠劵的话  并且商品总价大于满的金额 赠送优惠劵
            if ($value['pattern_id'] == 3 && $place_price > $value['full_price']) {
                $voucher_place_info = db('voucher')->where(['voucher_id' => $value['voucher_id']])->find();
                $voucher_data = [
                    'member_id' => $member_id,
                    'voucher_type_id' => 3,
                    'voucher_id' => $value['voucher_id'],
                    'voucher_name' => $voucher_place_info['voucher_title'],
                    'is_used' => 1,
                    'create_time' => time(),
                    'due_time' => time() + ($voucher_place_info['use_date'] * 24 * 60 * 60),
                    'voucher_collection_price' => $voucher_place_info['voucher_price']
                ];
                db('voucher_collection')->insert($voucher_data);
            }
        }
        // //保存数据
        $this->_order_data['order_id'] = $order_project_id;
        $this->_order_data['pay_sn'] = $pay_sn;
        $this->_order_data['payment_code'] = 'alipay';
        $this->_order_data['order_sn'] = $order_project['order_sn'];
    }

    /**
     * 得到所购买的id和数量
     *
     */
    private function _prodectItems($project_id)
    {
        //存放所购商品ID和数量组成的键值对
        $where['project_id'] = $project_id;
        $project_goods = db('goodsprojectnums')->where($where)->column('goods_id,num');
        return $project_goods;
    }


    /**
     * 第一步：处理立即购买
     * @param type $cart_id 购物车
     * @param type $member_id 会员编号
     * @param type $store_id 店铺编号
     * @param type $extra 额外特殊判断处理数据，比如拼团功能
     * @return type
     */
    public function getGoodsList2($project, $member_id, $store_id, $extra = array(), $is_install = '0')
    {
        //取得POST ID和购买数量
        $buy_items = $this->_parseItems($project);
        if (empty($buy_items)) {
            return ds_callback(false, '所购商品无效');
        }
        $goods_info['is_install'] = $is_install;
        $goods_id = key($buy_items);
        $quantity = current($buy_items);

        //商品信息[得到最新商品属性及促销信息]
        $goods_info = $this->_logic_buy_1->getGoodsOnlineInfo($goods_id, intval($quantity), $extra, $member_id);
        // p($goods_info);die;
        if (empty($goods_info)) {
            return ds_callback(false, '商品已下架或不存在');
        }

        //不能购买自己店铺的商品
        if ($goods_info['store_id'] == $store_id) {
            return ds_callback(false, '不能购买自己店铺的商品');
        }
        $store_id = get_parent_store_id();
        //p($store_id);die;
        $supplier_type = get_supplier_type();
        #shen 判断价格是否相同
        if ($supplier_type == 1) {
            #加价
            $y_goods_info = db('y_goods')->where('store_id', $store_id)->where('goods_id', $goods_info['goods_id'])->find();
            // p($goods_info);die;


            if ($is_install == 1) {
                #含有安装
                $goods_info['goods_price'] = (float)$goods_info['install_money'] + (float)$goods_info['gu_final_price'] + (float)$y_goods_info['price'];
            } else {
                $goods_info['goods_price'] = (float)$goods_info['gu_final_price'] + (float)$y_goods_info['price'];
            }
        } else {
            #按照提成走
            if ($is_install == 1) {
                #含有安装
                $goods_info['goods_price'] = (float)$goods_info['install_money'] + (float)$goods_info['ti_final_price'];
            } else {
                $goods_info['goods_price'] = (float)$goods_info['ti_final_price'];
            }
        }

        $config = db('config')->where('code', 'qiniu_http')->find();
        $goods_info['goods_image_url'] = $config['value'] . '/' . $goods_info['goods_image'];


        //进一步处理数组
        $store_cart_list = array();
        $goods_list = array();
        $goods_list[0] = $store_cart_list[$goods_info['store_id']][0] = $goods_info;

        return ds_callback(true, '', array('goods_list' => $goods_list, 'store_cart_list' => $store_cart_list));
    }


    /**
     * 购买第一步
     * @param type $project_id 项目id
     * @param type $ifcart
     * @param type $member_id
     * @param type $store_id
     * @param type $extra 额外特殊判断处理数据，比如拼团功能
     * @return type
     */
    public function buyStep1_project($project_id, $member_id)
    {
        //获取项目定制的商品信息
        $result = $this->getGoodsList_project($project_id, $member_id);

        if (!$result['code']) {
            return $result;
        }

        //获取所有收货地址，用户积分，用户可用的优惠劵列表
        $result['data']['information'] = $this->getBuyStep1Data_project($member_id, $result['data']);

        return $result;
    }

    /**
     * 购买第一步：返回商品、促销、地址、发票等信息，然后交前台抛出
     * @param unknown $member_id
     * @param unknown $data 商品信息
     * @return
     */
    public function getBuyStep1Data_project($member_id, $data)
    {
        $project_info = $data['project_info'];

        //获取用户可用的优惠劵列表
        list($voucher_list) = $this->voucher_project($member_id, $project_info['total_price']);
        $result['voucher_list'] = $voucher_list;


        //输出用户默认收货地址
        $result['address_info'] = model('address')->getDefaultAddressInfo(array('member_id' => $member_id));

        // 获取用户表信息（返回积分）
        list($integral_ratio) = $this->_logic_buy_1->getProjectIntegral($member_id);
        $result['integral_ratio'] = $integral_ratio;

        return $result;
    }

    /**
     * 购买第一步
     * @param type $project_id 项目id
     * @param type $ifcart
     * @param type $member_id
     * @param type $store_id
     * @param type $extra 额外特殊判断处理数据，比如拼团功能
     * @return type
     */
    public function buyStep1_equipment($member_id, $order_id, $confirm_type)
    {

        //获取所有收货地址，用户积分，用户可用的优惠劵列表
        $result = $this->getBuyStep1Data_equipment($member_id, $order_id, $confirm_type);

        return $result;
    }

    /**
     * 购买第一步：返回商品、促销、地址、发票等信息，然后交前台抛出
     * @param unknown $member_id
     * @param unknown $data 商品信息
     * @return
     */
    public function getBuyStep1Data_equipment($member_id, $order_id, $confirm_type)
    {
        $order_info = db('s_order')->where(['order_id' => $order_id])->find();

        if ($confirm_type == 1) { #1--设备 2--追加工时
            //返回订单信息
            $result['order_info'] = $order_info;

            $count_price = $order_info['order_amount']; #总价格

            //返回所有设备
            $equipment_list = db('s_order_detail')->where(['order_id' => $order_id])->select();

            $result['equipment_list'] = [];
            foreach ($equipment_list as $key => $value) {
                $result['equipment_list'][$key]['goods_name'] = $value['goods_name'];
                $result['equipment_list'][$key]['b_name'] = $value['b_name'];
                $result['equipment_list'][$key]['type_model'] = $value['type_model'];
            }
        } else {
            $append_info = db('s_order_append')->where(['id' => $order_id])->find();

            $originator_info = db('fuwu_personal')->where(['id' => $append_info['originator']])->find();

            $name = $originator_info['name'];

            if ($append_info['originator'] == 0) {
                $name = '管理员';
            }
            $append_list = [
                'originator' => $name,
                'add_hours' => $append_info['add_hours'],
                'created_at' => date('Y-m-d H:i:s', $append_info['created_at']),
                'hours_price' => $append_info['add_hours'] * $append_info['payper_hour'],
            ];
            $result['append_info'] = $append_list;

            $count_price = $append_info['add_hours'] * $append_info['payper_hour']; #总价格
        }

        //获取用户可用的优惠劵列表
        list($voucher_list) = $this->voucher_equipment($member_id, $count_price, $order_info['order_type']);
        $result['voucher_list'] = $voucher_list;

        //输出用户默认收货地址
        $result['address_info'] = model('address')->getDefaultAddressInfo(array('member_id' => $member_id));

        // 获取用户表信息（返回积分）
        list($integral_ratio) = $this->_logic_buy_1->getProjectIntegral($member_id);
        $result['integral_ratio'] = $integral_ratio;

        return $result;
    }

    /**
     * 项目定制第一步：处理立即购买
     * @param type $cart_id 购物车
     * @param type $member_id 会员编号
     * @param type $store_id 店铺编号
     * @param type $extra 额外特殊判断处理数据，比如拼团功能
     * @return type
     */
    public function getGoodsList_project($project_id, $member_id)
    {

        //获取到项目定制的详细信息
        $where['project_id'] = $project_id;
        $where['status'] = 1;

        $project_info = db('goodsproject')->where($where)->find();
        if ($project_info['status'] == 0) {
            return ds_callback(false, '该项目已下架');
        }
        $config = db('config')->where('code', 'qiniu_http')->find();

        $project_info['goods_image_url'] = $config['value'] . '/' . $project_info['project_images'];

        $project_info['goods_total_price'] = $project_info['total_price'];
        // $project_info['total_price'] = $project_info['total_price'] + $project_info['fee_price'] + $project_info['charge_price'] + $project_info['plementation_price'];
        $project_info['total_price'] = $project_info['total_price'];
        if (empty($project_info['goods_commonid'])) {
            return ds_callback(false, '所购商品无效');
        }

        //获取所有商品信息
        //字符串转数组
        $goods_array = explode(",", $project_info['goods_commonid']);
        $goods_info = [];
        foreach ($goods_array as $key => $value) {
            $goods_info[] = db('goodscommon')->where(['goods_commonid' => $value])->find();
        }


        return ds_callback(true, '', array('project_info' => $project_info, 'goods_info' => $goods_info));
    }

    //    用户项目定制优惠券列表
    public function voucher_project($member_id = '', $price)
    {

        //返回优惠劵列表
        // 1、首先查询当前用户所有的优惠劵列表
        $voucher_user_list = db('voucher_collection')->where(['member_id' => $member_id, 'is_used' => 1])->select();

        //2、遍历优惠劵列表，用于判断是否满足限制条件

        $voucher_list = [];
        foreach ($voucher_user_list as $key => $value) {

            //找到优惠劵表，获取限制条件
            $parms_voucher['voucher_id'] = $value['voucher_id'];
            $parms_voucher['voucher_state'] = 1;
            $parms_voucher['status'] = 1;
            $parms_voucher['is_del'] = 0;
            $parms_voucher['vou_type'] = 3;
            $voucher_conditions = db('voucher')->where($parms_voucher)->find();
            //获取优惠劵列表
            $new_voucher_list = db('voucher_collection')->alias('vc')->join('voucher v', 'v.voucher_id=vc.voucher_id')->where(['vc.id' => $value['id']])->find();
            //1、判断结束时间  2、如果商品总价 大于 优惠劵限制金额条件的话  可以用
            if (!empty($voucher_conditions) && $voucher_conditions['vou_type'] == 3 && $value['due_time'] > time() && $price > $voucher_conditions['voucher_limit']) {
                $voucher_list[] = $new_voucher_list;
            }
        }
        return array($voucher_list);
    }

    /**
     * Notes:服务单优惠券列表
     * User: shen
     * Date: 2020/5/14
     * Time: 14:28
     * @param string $member_id
     * @param $price
     * @param int $order_type
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function voucher_equipment($member_id = '', $price, $order_type = 0)
    {

        #领取优惠券表条件
        $where = array();
        $where['vu.due_time'] = array('>', time());
        $where['vu.member_id'] = array('eq', $member_id);
        $where['vu.is_used'] = array('eq', 1);
        $where['vu.is_send_del'] = array('eq', 0);
        $where['vu.due_time'] = array('gt', time());
        #优惠券条件
        $where['v.voucher_state'] = array('eq', 1);
        $where['v.status'] = array('eq', 1);
        $where['v.is_del'] = array('eq', 0);
        $where['v.vou_type'] = array('eq', 2);
        $where['v.voucher_enddate'] = array('gt', time());
        $where['v.voucher_limit'] = array('lt', $price);
        if ($order_type > 0) {
            if ($order_type == 1) { #安装
                $where['v.vou_gcid'] = array('eq', 3);
            } else if ($order_type == 2) { #维修
                $where['v.vou_gcid'] = array('eq', 2);
            } else if ($order_type == 3) { #移除
                $where['v.vou_gcid'] = array('eq', 4);
            } else { #保养
                $where['v.vou_gcid'] = array('eq', 1);
            }
        }
      //  p($where);die;
        $voucher_list = db('voucher_collection')->alias('vu')->join('voucher v', 'v.voucher_id=vu.voucher_id')
            ->where($where)->select();
        return array($voucher_list);
    }

    /**
     * 服务单第一步：处理立即购买
     * @param type $cart_id 购物车
     * @param type $member_id 会员编号
     * @param type $store_id 店铺编号
     * @param type $extra 额外特殊判断处理数据，比如拼团功能
     * @return type
     */
    public function getGoodsList_service($service_id, $member_id)
    {

        $service_info = db('new_equipment_brand')->alias('neb')
            ->join('new_equipment ne', 'ne.id = neb.equipment_id')
            ->field('ne.id,ne.goods_name,neb.equipment_brand_id,neb.brand_name,neb.option,neb.science,neb.spec_value_type')
            ->where(['equipment_brand_id' => $service_id])->find();

        $goods_info = [];
        return ds_callback(true, '', array('service_info' => $service_info, 'goods_info' => $goods_info));
    }
}
